977. Squares of a Sorted Array有序数组的平方

网址:https://leetcode.com/problems/squares-of-a-sorted-array/

双指针法

把左端的元素和右端的元素比较后挑出绝对值大的,将其平方放入ans中,并且将指针往中间移动

不断循环上述过程,直至两指针重合。注意处理重合位置

最后将 ans 通过 reverse 反转一下就可以了

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int i = 0, j = A.size()-1;
        vector<int> ans;
        while(i != j)
        {
            if(abs(A[i]) < abs(A[j]))
            {
                ans.push_back(A[j]*A[j]);
                j--;
            }
            else
            {
                ans.push_back(A[i]*A[i]);
                i++;
            }
        }
        ans.push_back(A[i]*A[i]);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

原文地址:https://www.cnblogs.com/tornado549/p/10678839.html