ac solution code


  • 1
        /*
         Solution1. Swap - O(n) - BETTER (<n); space = O(1)
         Use index as right boundary of non-zero elements: nums[0...index] are non-zero. If meet no-zero element, swap nums[i] and nums[index], meanwhile advance index.
         */
        func moveZeroes(_ nums: inout [Int]) {
            var index = 0 // Right boundary of non-zero elements: nums[0...index] are non-zero
            for i in 0 ..< nums.count {
                if nums[i] != 0 {
                    if (i != index) {// If meet no-zero element, swap nums[i] and nums[index], meanwhile advance index.
                        swap(&nums[index], &nums[i])
                    }
                    index += 1
                }
            }
        }
    
        /*
         Solution2. Mine - No swap - O(n) - (=n); space = O(1)
         Put all none-zero numbers before index till i pointer reaches the end of numbers, then fill 0 into nums[index...n-1]. No swap needed.
         */
        func moveZeroes(_ nums: inout [Int]) {
            var index = 0 // right boundary of non-zero elements: nums[0...index] are non-zero
            for i in 0 ..< nums.count {
                if nums[i] != 0 {
                    nums[index] = nums[i]
                    index += 1
                }
            }
            while index < nums.count {// After i pointer reaches the end of numbers, then fill 0 into nums[index...n-1]
                nums[index] = 0
                index += 1
            }
        }
    

    0_1484626713519_Evernote Camera Roll 20170116 201425.jpg


Log in to reply
 

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