-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0977.cpp
More file actions
42 lines (38 loc) · 788 Bytes
/
0977.cpp
File metadata and controls
42 lines (38 loc) · 788 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
41
42
class Solution {
public:
vector<int> sortedSquares(vector<int> &A) { return func1(A); }
// ** two pointer
vector<int> func1(vector<int> &A) {
vector<int> res;
int lf = -1, rt = -1;
for (int i = 0; i < A.size(); i++) {
if (A[i] > 0) {
rt = i;
lf = i - 1;
break;
}
}
if (rt == -1) {
rt = A.size();
lf = rt - 1;
}
while (lf >= 0 && rt < A.size()) {
if (A[lf] * A[lf] < A[rt] * A[rt]) {
res.push_back(A[lf] * A[lf]);
lf--;
} else {
res.push_back(A[rt] * A[rt]);
rt++;
}
}
while (lf >= 0) {
res.push_back(A[lf] * A[lf]);
lf--;
}
while (rt < A.size()) {
res.push_back(A[rt] * A[rt]);
rt++;
}
return res;
}
};