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:
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
solution1 (another array? not good)
func moveZeroes(nums []int) {
insert := 0
for _,v:= range nums{
if v != 0 {
nums[insert] = v
insert += 1
}
}
for insert < len(nums) {
nums[insert] = 0
insert += 1
}
}
solution2 (better)
func moveZeroes(nums []int) {
insert := 0
for _,v:= range nums{
if v != 0 {
nums[insert] = v
insert += 1
}
}
for insert < len(nums) {
nums[insert] = 0
insert += 1
}
}