LeetCode: 283. Move Zeroes
Summary
Given an integer array nums, move all 0s to the end while keeping the relative order of non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Approach
Two-pointer approach.
- Pointer
iscans each element from left to right. - Pointer
zero_idxstores the leftmost index where a0should be replaced by the next non-zero value.
Function
Initialization:
zero_idx = -1
For each number n at index i in nums:
- If
n == 0andzero_idx < 0, setzero_idx = i(initialize zero pointer). - Else, if
n != 0andzero_idx >= 0:- Swap
nums[zero_idx]andnums[i]. - Increment
zero_idxby1.
- Swap
Example:
Input: nums = [0,1,0,3,12]
n = 0ati = 0->zero_idx = 0n = 1ati = 1-> swapnums[0]andnums[1]->[1,0,0,3,12],zero_idx = 1n = 0ati = 2-> skipn = 3ati = 3-> swapnums[1]andnums[3]->[1,3,0,0,12],zero_idx = 2n = 12ati = 4-> swapnums[2]andnums[4]->[1,3,12,0,0]
Return nums.
Complexity
Time complexity: O(N), where N is the size of nums.
Space complexity: O(1) since the operation is in-place.