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优化

相关文章
相关标签/搜索