977. Squares of a Sorted Array
Easy
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?
解題
暴力解(超級慢!),先平方再sort。
改良後的方法,log(n)。
因為input 的數列已經依照大小排列好,所以使用兩個指針,一個指向頭,一個指向尾,來比較其絕對值大小,將較大的數字放進答案陣列中後移動指針。
Runtime: 19 ms, faster than 99.75%
Memory Usage: 6.6 MB, less than 95.67%
Last updated