LeetCode之Sort Array By Parity(Kotlin)

嘟囔發表於2019-01-01

問題: 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())
}
複製程式碼

有問題隨時溝通

具體程式碼實現可以參考Github

相關文章