LeetCode之Squares of a Sorted Array(Kotlin)

問題: 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.git

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
 

Note:

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
複製代碼

方法: 先以O(n)複雜度遍歷將元素修改成平方,而後用快速排序的複雜度將數組進行排序,後續要優化爲總體O(n)的複雜度。github

具體實現:數組

class SquaresOfASortedArray {
    fun sortedSquares(A: IntArray): IntArray {
        for (index in A.indices) {
            A[index] *= A[index]
        }
        Arrays.sort(A)
        return A
    }
}

fun main(args: Array<String>) {
    val input = intArrayOf(-4, -1, 0, 3, 10)
    val squaresOfASortedArray = SquaresOfASortedArray()
    CommonUtils.printArray(squaresOfASortedArray.sortedSquares(input).toTypedArray())
}
複製代碼

有問題隨時溝通bash

具體代碼實現能夠參考Github優化

相關文章
相關標籤/搜索