LeetCode: 905. Sort Array By Parity / 奇偶排序

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.

Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000

我的解法

class Solution {
    func sortArrayByParity(_ A: [Int]) -> [Int] {
        var first = 0
        var last = A.count - 1
        var list = A
        while first < last {
            
            if 0 != list[first] % 2 { // 第一位基数
                list.swapAt(first, last)
                last -= 1
            } else {
                first += 1
            }
            
            if 0 == list[last] % 2 { // 最后一位偶数
                list.swapAt(first, last)
                first += 1
            } else {
                last -= 1
            }
        }
        
        return list
    }
}

LeetCode地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。