問題: 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())
}
複製程式碼
有問題隨時溝通