Leetcode - Move Zeroes
https://leetcode.com/problems/move-zeroes/
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
I've done such problems for ten thousand times.
func moveZeroes(nums []int) { left := 0 right := left + 1 for right < len(nums) { for left < len(nums) && nums[left] != 0 { left++ } right = left+1 for right < len(nums) && nums[right] == 0 { right++ } if right >= len(nums) { break } nums[left] = nums[right] nums[right] = 0 left++ } }