-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0977.cpp
More file actions
36 lines (35 loc) · 981 Bytes
/
Copy path0977.cpp
File metadata and controls
36 lines (35 loc) · 981 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
// Intuitive solution
class Solution {
public:
vector<int> sortedSquares(vector<int> &nums) {
vector<int> res;
int i = 0, j = nums.size() - 1;
while (i <= j) {
int n1 = nums[i] * nums[i];
int n2 = nums[j] * nums[j];
if (n1 > n2) {
res.push_back(n1);
i++;
} else {
res.push_back(n2);
j--;
}
}
reverse(res.begin(), res.end());
return res;
}
};
// Intuitive solution, better execution
// avoids recomputation of squares
// avoids reversal of the array
class Solution {
public:
vector<int> sortedSquares(vector<int> &nums) {
int n = nums.size(), i = 0, j = nums.size() - 1;
vector<int> res(n);
for_each(nums.begin(), nums.end(), [](int &a) { a *= a; });
while (i <= j)
res[--n] = nums[i] > nums[j] ? nums[i++] : nums[j--];
return res;
}
};