977 - Squares of a Sorted Array

解法一 - Two Pointer

這題的 Two pointer 思路如下:

class Solution {
public:
    vector<int> sortedSquares(vector<int>& arr) {
        int n = arr.size();
        vector<int> squares(n);

        int highestIdx = n-1;
        int l=0, r=n-1;
        while(l <= r) {
            int leftSquare = pow(arr[l], 2);
            int rightSquare = pow(arr[r], 2);

            if(leftSquare >= rightSquare) {
                squares[highestIdx--] = leftSquare;
                l++;
            }
            else {
                squares[highestIdx--] = rightSquare;
                r--;
            }
        }

        return squares;
    }
};

results matching ""

    No results matching ""