977. 有序数组的平方 双指针

977. 有序数组的平方

相向双指针

思路
nums数组非递减,平方后最大值一定在待排序区间的最两端(最左端 left 或最右端 right),每次循环取最大值添加到res数组中,
更新对应的边界缩小区间,重复上述过程直至 left > right。

class Solution {
    public int[] sortedSquares(int[] nums) {
        int k = nums.length;
        int left = 0;
        int right = k - 1;
        int[] res = new int[k];
        // 对每个元素做平方运算
        for (int i = 0; i < k; i++) {
            nums[i] = nums[i] * nums[i];
        }
        // 最大值不是在待处理区间最左端,就是在最右端
        while (left <= right) {
            if (nums[left] < nums[right] ) {
                res[--k] = nums[right];
                right--;
            } else {
                res[--k] = nums[left];
                left++;
            }
        }
        return res;
    }
}
posted @ 2025-10-12 21:05  Nickey103  阅读(9)  评论(0)    收藏  举报