面试题21. 调整数组顺序使奇数位于偶数前面
2020-03-26 本文已影响0人
寂灭天骄小童鞋
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
}