Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created June 21, 2019 00:32
Show Gist options
  • Select an option

  • Save davidinga/ae24837b7e221cfdc3eb4b02b1e152b5 to your computer and use it in GitHub Desktop.

Select an option

Save davidinga/ae24837b7e221cfdc3eb4b02b1e152b5 to your computer and use it in GitHub Desktop.
Shift all zeros in array to the right most indexes in linear time.
func shiftZeros(in array: inout [Int]) {
var indexToPlaceZero = array.count - 1
for i in array.indices {
if array[i] == 0 {
while array[indexToPlaceZero] == 0, i < indexToPlaceZero {
indexToPlaceZero -= 1
}
array.swapAt(i, indexToPlaceZero)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment