Skip to content

Commit ec982af

Browse files
author
Yi Gu
committed
[Sort] Add solution to Sort Transformed Array
1 parent d3f521a commit ec982af

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Sort/SortTransformedArray.swift

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/sort-transformed-array/
3+
* Primary idea: Compare head and tail and put larger/smaller one to end/start of array,
4+
* according to a is less than 0 or not
5+
* Time Complexity: O(n), Space Complexity: O(1)
6+
*/
7+
8+
class SortTransformedArray {
9+
func sortTransformedArray(_ nums: [Int], _ a: Int, _ b: Int, _ c: Int) -> [Int] {
10+
var res = [Int](repeating: 0, count: nums.count)
11+
var left = 0
12+
var right = res.count - 1
13+
var index = a >= 0 ? nums.count - 1 : 0
14+
15+
while left <= right {
16+
let leftVal = getRes(a, b, c, nums[left])
17+
let rightVal = getRes(a, b, c, nums[right])
18+
19+
if a >= 0 {
20+
if leftVal > rightVal {
21+
res[index] = leftVal
22+
left += 1
23+
} else {
24+
res[index] = rightVal
25+
right -= 1
26+
}
27+
index -= 1
28+
} else if a < 0 {
29+
if leftVal < rightVal {
30+
res[index] = leftVal
31+
left += 1
32+
} else {
33+
res[index] = rightVal
34+
right -= 1
35+
}
36+
index += 1
37+
}
38+
}
39+
40+
return res
41+
}
42+
43+
private func getRes(_ a: Int, _ b: Int, _ c: Int, _ x: Int) -> Int {
44+
return a * x * x + b * x + c
45+
}
46+
}

0 commit comments

Comments
 (0)