https://leetcode.com/problems/squares-of-a-sorted-array/
两个指针i,j,分别指向头和尾,平方后比较:
若相等,则将元素的平方压入数组result,左指针i右移;
反之,将较大的元素平方压入数组result,较大的指针向另一个指针移动;
压入最后一个元素,将result数组取反。
class Solution {
public:vector<int> sortedSquares(vector<int>& A) {vector<int> result;if(A.size()==0)return result;if(A.size()==1){result.push_back(A[0]*A[0]);return result;}int i = 0, j = A.size()-1;while(i<j){while(i<j && A[i]*A[i]==A[j]*A[j]){result.push_back(A[i]*A[i]);//如果要求平方后不能有重复值,删除这一句即可i++;}if(i<j && A[i]*A[i]<A[j]*A[j]){result.push_back(A[j]*A[j]);j--;}else if(i<j && A[i]*A[i]>=A[j]*A[j]){result.push_back(A[i]*A[i]);i++;}}result.push_back(A[i]*A[i]);reverse(result.begin(), result.end());return result;}
};