283-move-zeroes
Question
https://leetcode.com/problems/move-zeroes/description/
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:
Given nums = [0, 1, 0, 3, 12],
after calling your function,
nums should be [1, 3, 12, 0, 0].
Thought Process
- Two Pointers
- Use one pointer to keep track the last inserted position
- Anther pointer moves forward as we progress the element
- Insert the element if it is not equal to 0
- Time complexity O(n)
- Space complexity O(1)
Solution
class Solution {
public void moveZeroes(int[] nums) {
int id = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) nums[id++] = nums[i];
}
while (id < nums.length) nums[id++] = 0;
}
}