题目描述

最容易想到的解法
class Solution {
func moveZeroes(_ nums: inout [Int]) {
for index in (0..<nums.count).reversed() {
if nums[index] == 0 {
moveZeroes(&nums, index)
}
}
}
func moveZeroes(_ nums: inout [Int], _ index: Int) {
var current = index
while current < nums.count - 1 {
nums.swapAt(current, current + 1)
current += 1
}
}
}
最优解 - 双指针
class Solution {
func moveZeroes(_ nums: inout [Int]) {
let length = nums.count
var left = 0, right = 0
while right < length {
if nums[right] != 0 {
nums.swapAt(left, right)
left += 1
}
right += 1
}
}
}