Leetcode:977. Squares of a Sorted Array

題目:
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

範例:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

在LeetCode中使用Golang的庫很方便
不用import
只要你standard的庫名正確就可使用
像是這題的sort庫

解法:

func sortedSquares(A []int) []int {
    for index, value := range A {
        A[index] = value*value
    }
    sort.Ints(A)
    return A
}

還記得寫完這題,我發現自己對節省記憶體的功力還很弱

發佈留言