[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 |
|
JavaScript实现
1 |
|