LeetCode之Squares of a Sorted Array(Kotlin)

555 阅读1分钟

问题: 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.

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)的复杂度。

具体实现:

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())
}

有问题随时沟通

具体代码实现可以参考Github