目录
解题过程:
描述:
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
提示
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
分析条件:
第一遍的思路:(错误思路)
当数组的长度为1时,直接返回这个数组
当数组的长度大于1时,我们从数组的第一个数开始遍历,遇到0,交换
比如 1 0 2 0 3 我们就把它变成 1 2 0 3 0 把遇到的第一个0交换到末尾
java
class Solution {
public void moveZeroes(int[] nums) {
if(nums.length == 1){
return;
}
// 0 1 0 3 12
for(int i = 0;i < nums.length;i++){
if(nums[i] != 0){
continue;
}
for(int j = i;j < nums.length - 1;j++){
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
这种写法只通过了28/75个用例,原因是 [0,0,1] 如果0连续,那么这种逻辑会漏掉一些0
正确解题思路:
java
class Solution {
public void moveZeroes(int[] nums) { 1 1 0
//1 2 0 3 12
int n = nums.length;
//left为左指针,left索引左边的数均为已处理数
int left = 0;
//rigth为右指针,right索引不断右移寻找非0数
int right = 0;
while(right < n){
//(nums[right] != 0时再交换,这段逻辑可以保证left和right一起移动到第一个num[n] = 0处,
//此时left = n,right = n,下一步left = n,right = n + 1,right开始寻找非0数
if(nums[right] != 0){
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;
left++;
}
right++;
}
}
}
通过这道题可以学到什么:
1.数组的长度,nums.length 后面不加()!
2.while循环中,我们要用nums[right != 0]作为条件,这样可以带着left和right一起移动到数组中第一个0处