問題: Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition.git
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
複製代碼
方法: 兩個index同時遍歷,若是遇到兩個數組元素都不符合規則則互相交換位置,遍歷整個數組後輸出數組則爲最終結果。github
具體實現:數組
class SortArrayByParityII {
fun sortArrayByParityII(A: IntArray): IntArray {
var oddIndex = 1
var evenIndex = 0
var temp : Int
while(oddIndex <= A.lastIndex && evenIndex <= A.lastIndex) {
if (A[evenIndex] % 2 != 0 && A[oddIndex] % 2 != 1) {
temp = A[oddIndex]
A[oddIndex] = A[evenIndex]
A[evenIndex] = temp
}
if (A[evenIndex] % 2 == 0) {
evenIndex += 2
}
if (A[oddIndex] % 2 == 1) {
oddIndex += 2
}
}
return A
}
}
fun main(args: Array<String>) {
val array = intArrayOf(4,2,5,7)
val sortArrayByParityII = SortArrayByParityII()
CommonUtils.printArray(sortArrayByParityII.sortArrayByParityII(array).toTypedArray())
}
複製代碼
有問題隨時溝通bash