問題: Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition.git
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
複製代碼
方法: 數組左右逼近,遇到奇偶數字則交換,指針在中間位置相遇時中止,輸出最後的數組即爲結果。github
具體實現:數組
class SortArrayByParity {
fun sortArrayByParity(A: IntArray): IntArray {
var i = 0
var j = A.lastIndex
var temp: Int
while (i < j) {
if (A[i].rem(2) != 1) {
i++
continue
}
if (A[j].rem(2) != 0) {
j--
continue
}
temp = A[i]
A[i] = A[j]
A[j] = temp
}
return A
}
}
fun main(args: Array<String>) {
val array = intArrayOf(3, 1, 2, 4)
val sortArrayByParity = SortArrayByParity()
CommonUtils.printArray(sortArrayByParity.sortArrayByParity(array).toTypedArray())
}
複製代碼
有問題隨時溝通bash