-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsortedSquares.go
More file actions
40 lines (31 loc) · 756 Bytes
/
Copy pathsortedSquares.go
File metadata and controls
40 lines (31 loc) · 756 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* https://leetcode.com/problems/squares-of-a-sorted-array/
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
*/
package larray
func sortedSquares(A []int) []int {
p, i := -1, 0
for ; i < len(A) && A[i] < 0; i++ {
p = i
}
res := make([]int, len(A), len(A))
for idx := 0; idx < len(A); idx++ {
if p < 0 || (i < len(A) && A[i] < -A[p]) {
res[idx] = A[i] * A[i]
i++
} else {
res[idx] = A[p] * A[p]
p--
}
}
return res
}