-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path977. Squares of a Sorted Array.cpp
More file actions
39 lines (36 loc) · 1.31 KB
/
Copy path977. Squares of a Sorted Array.cpp
File metadata and controls
39 lines (36 loc) · 1.31 KB
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
//https://leetcode.com/problems/squares-of-a-sorted-array/
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
vector<int> result;
//Find the first non negative number,
// and then consider them as two different array which need to be merged.
int positiveIndex = 0;
for(; positiveIndex < A.size(); ++positiveIndex) {
if ( A[positiveIndex] > 0 ) {
break;
}
}
int negativeIndex = positiveIndex - 1;
while(negativeIndex >= 0 && positiveIndex < A.size()) {
if ( abs(A[negativeIndex]) < A[positiveIndex] ) {
result.push_back( A[negativeIndex] * A[negativeIndex]);
--negativeIndex;
} else {
result.push_back( A[positiveIndex] * A[positiveIndex]);
++positiveIndex;
}
}
// Fill rest of the pending items.
while( negativeIndex >= 0) {
result.push_back( A[negativeIndex] * A[negativeIndex]);
--negativeIndex;
}
// Fill rest of the pending items.
while( positiveIndex < A.size()) {
result.push_back( A[positiveIndex] * A[positiveIndex]);
++positiveIndex;
}
return result;
}
};