977.双指针之有序数组的平方和
给你一个按 非递减顺序 排序的整数数组 nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
思路:双指针法
最大值可能存在最左边或者最右边。
设left = 0;right = arr.length - 1;
进行比较,将较大值存入新数组newArr的最后。
新数组中k来表示索引。
class Solution { public int[] sortedSquares(int[] nums) { int left =0; int right = nums.length -1; int k = nums.length - 1; int[] newArr = new int[nums.length]; while(left <= right){ if(nums[left] *nums[left] >= nums[right]*nums[right]){ newArr[k] = nums[left]*nums[left]; left++; k--; } else { newArr[k] = nums[right]*nums[right]; k--; right--; } } return newArr; } }