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:

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?

解題

暴力解(超級慢!),先平方再sort。

func sortedSquares(nums []int) []int {
    for i:=0; i<len(nums); i++ {
        nums[i] = nums[i]*nums[i]
    }
    
    sort.Ints(nums)
    return nums
}

改良後的方法,log(n)。

因為input 的數列已經依照大小排列好,所以使用兩個指針,一個指向頭,一個指向尾,來比較其絕對值大小,將較大的數字放進答案陣列中後移動指針。

Runtime: 19 ms, faster than 99.75%

Memory Usage: 6.6 MB, less than 95.67%

func sortedSquares(nums []int) []int {
    l := 0
    r := len(nums)-1
    length := len(nums)
    index := length-1
    
    ans := make([]int, length)
    
    for l <= r {
        if Abs(nums[l])>Abs(nums[r]) {
            ans[index] = nums[l]*nums[l]
            l++
        } else {
            ans[index] = nums[r]*nums[r]
            r--
        }
        index--
    }
    
    return ans
}

func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

Last updated