[LeetCode] 977. Squares of a Sorted Array

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)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int index = n - 1;
int left = 0;
int right = n - 1;
while (left <= right) {
if (Math.abs(nums[left]) > Math.abs(nums[right])) {
res[index--] = nums[left] * nums[left];
left++;
} else {
res[index--] = nums[right] * nums[right];
right--;
}
}
return res;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {number[]} A
* @return {number[]}
*/
var sortedSquares = function (A) {
let n = A.length;
let res = [n];
let i = 0;
let j = n - 1;
for (let p = n - 1; p >= 0; p--) {
if (Math.abs(A[i]) > Math.abs(A[j])) {
res[p] = A[i] * A[i];
i++;
} else {
res[p] = A[j] * A[j];
j--;
}
}
return res;
};

[LeetCode] 977. Squares of a Sorted Array
https://shurui91.github.io/posts/1991592077.html
Author
Aaron Liu
Posted on
February 29, 2020
Licensed under