ethan

ethan

新知,热爱生活,码农,读书
twitter
email
github

LCR 283. Move Zero

Given an array nums, write a function to move all 0's to the end of the array while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:

Input: nums = [0]
Output: [0]

Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

Solution 1: Two Pointers

func moveZeroes(nums []int)  {
	left, right, n := 0,0,len(nums)
	for right < n {
		if nums[right] != 0 {
			nums[left], nums[right] := nums[right], nums[left]
			left++
		}
		right++
	}
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.