题目:Move Zeroes
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.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
题目解析:把数组的0后移到最后,数字顺序保持不变。
One:把不为0的数目记录,同时把不为的数全部前移。最后把后几位置为0.
public class Solution {
public void moveZeroes(int[] nums) {
if(nums==null||nums.length==0)return;
int counter = 0;
int len = nums.length;
for(int i = 0;i<len;i++){
nums[i-counter] = nums[i];
if(nums[i]==0)
counter++;
}
for(int i =len-counter;i<len;i++){
nums[i] = 0;
}
}
}
Two:
public void moveZeroes(int[] nums) {
int j = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != 0) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
j++;
}
}
}