Created
June 21, 2019 00:32
-
-
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.
This file contains hidden or 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 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