Eagle233-Blog

[Algorithms] LeetCode 977. 有序数组的平方


Categories Algorithms Array
Tags

115 Words   |   1 Minutes

来源:代码随想录

LeetCode 977. 有序数组的平方

双指针法,倒序写进结果数组。

四刷:指针可以取等,为什么?

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int i = 0;
        int j = nums.size() - 1;
        vector<int> result(nums.size());
        int k = 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;
    }
};


Page views: Loading...  ·  Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号
Search