Back to Leetcode Go

283. Move Zeroes

website/content.en/ChapterFour/0200~0299/0283.Move-Zeroes.md

1.7.971.1 KB
Original Source

283. Move Zeroes

Problem

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 1:


Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  • You must do this in-place without making a copy of the array.
  • Minimize the total number of operations.

Problem Summary

The problem requires not using any extra auxiliary space, moving all 0 elements in the array to the end of the array, while maintaining the relative positions of all non-zero elements.

Solution Approach

This problem can be solved by scanning the array only once, continuously using i and j to mark 0 and non-zero elements, then swapping them with each other, ultimately achieving the goal of the problem. Similar problems include Problem 26, Problem 27, and Problem 80.

Code

go

package leetcode

func moveZeroes(nums []int) {
	if len(nums) == 0 {
		return
	}
	j := 0
	for i := 0; i < len(nums); i++ {
		if nums[i] != 0 {
			if i != j {
				nums[i], nums[j] = nums[j], nums[i]
			} 
			j++
		}
	}
}