leetcode 977. Squares of a Sorted Array 求一個數組的平方

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;
    }
};

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章