Skip to content

Commit cc7ea56

Browse files
committed
Add a solution to Squares of a Sorted Array
1 parent 220c9e0 commit cc7ea56

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Array/SquaresSortedArray.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/squares-of-a-sorted-array/
3+
* Primary idea: Two pointers. Compare absolute value and assign the bigger one to the right most index of the result.
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class SquaresSortedArray {
9+
func sortedSquares(_ nums: [Int]) -> [Int] {
10+
var left = 0, right = nums.count - 1, res = Array(repeating: 0, count: nums.count)
11+
var square = 0, idx = nums.count - 1
12+
13+
while left <= right {
14+
15+
if abs(nums[left]) < abs(nums[right]) {
16+
square = nums[right]
17+
right -= 1
18+
} else {
19+
square = nums[left]
20+
left += 1
21+
}
22+
23+
res[idx] = square * square
24+
idx -= 1
25+
}
26+
27+
return res
28+
}
29+
}

0 commit comments

Comments
 (0)