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.
题目解析:将数组中的零置后,不能复制数组,不能新建多余的数组
class Solution {
public void moveZeroes(int[] nums) {
if(nums==null||nums.length==0)return;
int a=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=0){
nums[a]=nums[i];
a+=1;
}
}
for(int j=a;j<nums.length;j++){
nums[j]=0;
}
}
}
如果该元素不为零,就将该元素的值放在第a个位置上,a为所有不为零的数的个数;之后将之后的位补零即可。
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++;
}
}
}
相当于遇到非零元素就将零与当前位置的元素交换