Given an integer array n u m s nums nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
example
Input:
n
u
m
s
=
[
−
4
,
−
1
,
0
,
3
,
10
]
nums = [-4, -1, 0, 3, 10]
nums=[−4,−1,0,3,10]
Output:
[
0
,
1
,
9
,
16
,
100
]
[0, 1, 9, 16, 100]
[0,1,9,16,100]
Explanation: After squaring, the array becomes
[
16
,
1
,
0
,
9
,
100
]
.
[16, 1, 0, 9, 100].
[16,1,0,9,100].
After sorting, it becomoes
[
0
,
1
,
9
,
16
,
100
]
[0, 1, 9, 16, 100]
[0,1,9,16,100]
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> res;
int n = nums.size();
for (auto num : nums) {
res.push_back(num * num);
}
sort(res.begin(), res.end());
return res;
}
};
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> res = nums;
int k = nums.size() - 1; // the index in the return vector
for (int i = 0, j = k; i <= j; ) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
res[k--] = nums[i] * nums[i];
++i;
} else {
res[k--] = nums[j] * nums[j];
--j;
}
}
return res;
}
};