Given an integer array nums, write a function to rearrange the array by moving all zeros to the end while keeping the order of non-zero elements unchanged. Perform this operation in-place without creating a copy of the array.
Input:
nums = [2,0,4,0,9]
Output:
[2,4,9,0,0]
Explanation
We can solve this problem by keeping a pointer i that iterates through the array and another pointer nextNonZero that points to the position where the next non-zero element should be placed. We can then swap the elements at i and nextNonZero if the element at i is non-zero. This way, we can maintain the relative order of the non-zero elements while moving all the zeroes to the end of the array.
Solution
def moveZeroes(nums): nextNonZero = 0 for i in range(len(nums)): if nums[i] != 0: nums[nextNonZero], nums[i] = nums[i], nums[nextNonZero] nextNonZero += 1
public static void moveZeroes(int[] nums) { int nextNonZero = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { int temp = nums[nextNonZero]; nums[nextNonZero] = nums[i]; nums[i] = temp; nextNonZero++; } }}
func moveZeroes(nums []int) { nextNonZero := 0 for i := 0; i < len(nums); i++ { if nums[i] != 0 { nums[nextNonZero], nums[i] = nums[i], nums[nextNonZero] nextNonZero++ } }}
function moveZeroes(nums: number[]): void { let nextNonZero: number = 0; for (let i: number = 0; i < nums.length; i++) { if (nums[i] !== 0) { [nums[nextNonZero], nums[i]] = [nums[i], nums[nextNonZero]]; nextNonZero++; } }}