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:
Example 2:
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?
这题,一看最简单的解法是直接sqrt然后sort,nlogn。后来看了solution,发现一个比较有趣的做法,2ptr。因为本来是sorted的array。所以一个指前,一个指尾。如果abs大的,就先sqrt and place在result array的最后。这样就可以O(n)了。
Last updated