283. Move Zeroes
by Botao Xiao
283. Move Zeroes
Question
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:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Thinking:
- Method 1:
class Solution {
public void moveZeroes(int[] nums) {
int len = nums.length;
int index = 0;
int count = 0;
for(int i = 0; i < len; i++){
if(nums[i] != 0){
nums[index++] = nums[i];
}else{
count++;
}
}
for(int i = len - count; i < len; i++)
nums[i] = 0;
}
}
Second time
class Solution {
public void moveZeroes(int[] nums) {
int cur = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
nums[cur++] = nums[i];
}
}
for(int i = cur; i < nums.length; i++)
nums[i] = 0;
}
}
Subscribe via RSS