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.
分析:本题不能新建一个数组来辅助排序,首先想到的便是双指针遍历排序数组。
代码:
public class Solution {
public void moveZeroes(int[] nums) {
for(int i = 0;i < nums.length;i++){
if(nums[i] == 0){
for(int j = i + 1;j < nums.length;j++){
if(nums[j] != 0){
nums[i] = nums[j];
nums[j] = 0;
break;
}
}
}
}
}
}
代码注释:1.先定义指针i,2.用指针i来遍历数组,当找到数组中第一个值为0的时候,启用第二个指针j;3.指针j从指针i的下一个值开始遍历,找到第一个不为零的值赋值给指针i指向的数,然后将指针j指向的数置零。4.依次遍历数组中所有数据,得到正确结果。
双指针的另一种表示形式为:
public class Solution {
public void moveZeroes(int[] nums) {
// for(int i = 0;i < nums.length;i++){
// if(nums[i] == 0){
// for(int j = i + 1;j < nums.length;j++){
// if(nums[j] != 0){
// nums[i] = nums[j];
// nums[j] = 0;
// break;
// }
// }
// }
// }
int i = 0;
int j = 0;
while(i < nums.length){
if(nums[i] == 0 || i == j){
i++;
}else{
if(nums[j] == 0){
nums[j] = nums[i];
nums[i] = 0;
i++;
}
j++;
}
}
}
}
图解: