当前位置:网站首页>2022-7-6 Leetcode 977. Square of ordered array

2022-7-6 Leetcode 977. Square of ordered array

2022-07-07 13:39:00 weixin_ fifty-one million one hundred and eighty-seven thousand

 Insert picture description here
Why should the cycle condition be set i <= j?
Because in the end i and j At the same time, point to the smallest number .

class Solution {
    
public:
    vector<int> sortedSquares(vector<int>& nums) {
    
        vector<int> result(nums.size(), 0);
        int k = nums.size()-1;
        int i = 0, j = nums.size()-1;
        while (i <= j){
    
            if (nums[i]*nums[i] < nums[j]*nums[j]){
    
                result[k--] = nums[j]*nums[j];
                j--;
            }else {
    
                result[k--] = nums[i]*nums[i];
                i++;
            }
        }
        return result;
    }
};
原网站

版权声明
本文为[weixin_ fifty-one million one hundred and eighty-seven thousand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071136083517.html