有序数组平方和

本题双指针所指示的区间状态是左闭右闭

class Solution {
    public int[] sortedSquares(int[] nums) {
        
        int[] res = new int[nums.length];

        int resIndex = nums.length - 1;

        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int leftVal = nums[left] * nums[left];
            int rightVal = nums[right] * nums[right];

            if (leftVal < rightVal) {
                res[resIndex] = rightVal;
                right--;
            } else {
                res[resIndex] = leftVal;
                left++;
            }

            resIndex--;
        }

        return res;
    }
}
posted @ 2024-07-31 21:39  Neking  阅读(16)  评论(0)    收藏  举报