Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。
//手撕 位置交换法
class Solution {
public void moveZeroes(int[] nums) {
int length = nums.length;
int left =0;
int right=0;
if(nums==null){
return;
}
while(right<length){
if(nums[right]!=0){
int temp =nums[left];
nums[left]=nums[right];
nums[right]=temp;
left++;
}
right++;
}
}
}
整个循环将快指针遇到的非零数与慢指针进行交换即能满足题目要求,保持相对位置且后移0。
//非零计数法
class Solution2 {
public void moveZeroes(int[] nums) {
if(nums==null) {
return;
}
//通过左指针记录有多少个非零数
int left = 0;
for(int right=0;right<nums.length;++right) {
if(nums[right]!=0) {
//left++ 先赋值后+1 目的将慢指针转变后移至下一覆盖位置
nums[left++] = nums[right];
}
}
//将剩余的非零数赋值为0
for(int i=left;i<nums.length;++i) {
nums[i] = 0;
}
}
}
前半循环将快指针非零数赋值给慢指针,这样会导致后面剩余交换n次的非零数,所以后半循环需要将它们转换为0,转换的起始位置就是慢指针的下一个位置。