Swift solution using a zero index variable


  • 0
    C
    class Solution {
        func moveZeroes(_ nums: inout [Int]) {
            //index for first zero
            var zeroStartIdx = -1
            for var idx in 0..<nums.count {
                if nums[idx] == 0 {
                    if zeroStartIdx < 0 {
                        zeroStartIdx = idx;
                    }
                } else if (nums[idx] != 0 && zeroStartIdx >= 0 && zeroStartIdx < idx) {
                    swap(nums: &nums, i: idx, j: zeroStartIdx)
                    zeroStartIdx = zeroStartIdx + 1;
                }
            }
        }
    
        func swap(nums:inout [Int], i: Int, j:Int) {
            let tmp = nums[i]
            nums[i] = nums[j]
            nums[j] = tmp
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.