问题:
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.
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.
方法:
数组左右逼近,遇到奇偶数字则交换,指针在中间位置相遇时停止,输出最后的数组即为结果。
具体实现:
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())
}
有问题随时沟通