左右指针的经典应用
左右下标元素平方相比,大的放新数组右边,比较简单,不赘述
class Solution {
public:
vector<int> sortedSquares(vector<int> &nums) {
int len = nums.size();
vector<int> res(len, 0);
int j = len - 1;
int left = 0;
int right = len - 1;
while (left <= right) {
int leftValue = pow(nums[left], 2);
int rightValue = pow(nums[right], 2);
if (leftValue < rightValue) {
res[j--] = rightValue;
right--;
} else {
res[j--] = leftValue;
left++;
}
}
return res;
}
};