Question: 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.
Example 1: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,7,4, 7] would also have been accepted.Copy the code
Method: Two indexes are iterated at the same time. If two array elements do not meet the rule, the positions of the two indexes are exchanged. The output of the array is the final result after iterating the entire array.
Concrete implementation:
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
}
}
returnA } } fun main(args: Array<String>) {Array = intArrayOf(4,2,5,7) val sortArrayByParityII = sortArrayByParityII () CommonUtils.printArray(sortArrayByParityII.sortArrayByParityII(array).toTypedArray()) }Copy the code
Feel free to communicate if you have any questions
Specific code implementation can refer to Github