977.有序数组的平方

18 阅读1分钟

image.png

  • 关键点
  • 不管正数还是负数,肯定是两边的平方后最大
  • 数组是从小到大,所以k要从最后逐渐递减
class Solution {
    public int[] sortedSquares(int[] nums) {
        int i = 0; //指向数组开头
        int j = nums.length - 1; // 指向结尾
        int k = nums.length - 1; // 用于新数组的索引
        int[] arr = new int[nums.length];
        for (; i <= j; k--) {
            if (nums[i] * nums[i] >= nums[j] * nums[j]) {
                arr[k] = nums[i] * nums[i];
                i++; //右移左指针
            } else {
                arr[k] = nums[j] * nums[j];
                j--;
            }

        }
        return arr;//返回新数组

    }
}