Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in non-decreasing order.
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n)
solution using a different approach?
有序数组的平方。
给你一个按 非递减顺序 排序的整数数组 nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
思路是 two pointer 夹逼。创建一个跟 input 同样长度的数组。因为 input 里面存在负数,而且很有可能存在一个绝对值非常大的负数,导致其平方值最大,所以需要 two pointer 左右指针比较哪个数字的绝对值大。细节实现参见代码。
时间O(n)
空间O(n) - output
JavaScript实现
1 /** 2 * @param {number[]} A 3 * @return {number[]} 4 */ 5 var sortedSquares = function (A) { 6 let n = A.length; 7 let res = [n]; 8 let i = 0; 9 let j = n - 1; 10 for (let p = n - 1; p >= 0; p--) { 11 if (Math.abs(A[i]) > Math.abs(A[j])) { 12 res[p] = A[i] * A[i]; 13 i++; 14 } else { 15 res[p] = A[j] * A[j]; 16 j--; 17 } 18 } 19 return res; 20 };
Java实现
1 class Solution { 2 public int[] sortedSquares(int[] nums) { 3 int len = nums.length; 4 int[] res = new int[len]; 5 int i = 0; 6 int j = nums.length - 1; 7 for (int p = len - 1; p >= 0; p--) { 8 if (Math.abs(nums[i]) > Math.abs(nums[j])) { 9 res[p] = nums[i] * nums[i]; 10 i++; 11 } else { 12 res[p] = nums[j] * nums[j]; 13 j--; 14 } 15 } 16 return res; 17 } 18 }