Last active
August 29, 2019 18:42
-
-
Save cristhianleonli/ad156a96a3e9ae7cdc253103223ac499 to your computer and use it in GitHub Desktop.
Given the array [1,0,9,8,5,4,0,0,5] move all zeros to the left side of the array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func moveZeros(array l: [Int]) -> [Int] { | |
var array = l | |
var zeroPointer = array.count - 1 | |
var i = array.count - 1 | |
while i >= 0 { | |
if array[i] != 0 { | |
array[zeroPointer] = array[i] | |
zeroPointer -= 1 | |
} | |
i -= 1 | |
} | |
while zeroPointer >= 0 { | |
array[zeroPointer] = 0 | |
zeroPointer -= 1 | |
} | |
return array | |
} | |
let array = [1, 0, 2, 0, 3, 4, 10, 6, 7] | |
let result = moveZeros(array: array) | |
print(result) // prints "[0, 0, 1, 2, 3, 4, 10, 6, 7]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment