977. 有序数组的平方

376 阅读1分钟

描述

image.png

思路

  • 把原数组每个数字平方后,得到的是前半段降序,后半段升序的数组。
  • 碰撞双指针填充到新数组中

代码

class Solution {
    public int[] sortedSquares(int[] nums) {
        // 把原数组给平方了
        for (int i = 0; i < nums.length; i++) {
            nums[i] *= nums[i]; 
        }
        // 结果集
        int[] res = new int[nums.length];
        // 碰撞指针,从后往前由大到小添加
        int i = 0, j = nums.length - 1, k = nums.length - 1;
        while (i <= j) {//注意是 <= !!!!
            if (nums[i] > nums[j]) {
                res[k] = nums[i];
                i++;
            } else {
                res[k] = nums[j];
                j--;
            }
            k--;
        }
        return res;
    }
}