面试题21. 调整数组顺序使奇数位于偶数前面

https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/

func exchange(_ nums: [Int]) -> [Int] {
    var result = nums
    var l = 0
    var r = nums.count - 1
    while l < r {
        //奇数,头指针向后前进
        if nums[l] % 2 == 1 {
            l = l + 1
            continue
        }
        //偶数,尾指针向前
        if nums[r] % 2 == 0 {
            r = r - 1
            continue
        }
        //不满足头指针指奇数 or  尾指针指偶数,=交换位置,然后idx继续前进
        result.swapAt(l, r)
        l = l + 1
        r = r - 1
    }
    return result
}

你可能感兴趣的:(面试题21. 调整数组顺序使奇数位于偶数前面)