一个思路1:
发现一个0,互相交换,把0移动到最后,然后把这个数组当成新数组,再来一次,所以是三重循环,时间效率很差
class Solution {
public void moveZeroes(int[] nums) {
int flag=0;
while(flag<nums.length){
for(int i=0;i<nums.length;i++){
if(nums[i]==0){
for(int j=i;j<nums.length-1;j++){
int temp=nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
}
}
}
flag++;
}
}
}思路2:
只跑一遍,过程中,把第一个0,和0之后的第一个非0交换;
public void moveZeroes(int[] nums) { int behind=0;//之前一个数肯定是非0,因为只有非0,才会++ int find=0; while(find<nums.length){ //如果没有发现0,那么behind和find是相等的,所以交换没用
//一旦之前那次发现了0,那么behind就停在之前那个位置,而find会继续走,知道走到下一个非0,此时,将这个非0和前面的behind交换 if(nums[find]!=0){ int temp=nums[behind]; nums[behind]=nums[find]; nums[find]=temp; behind++; } find++; } } public void moveZeroes(int[] nums) {
int behind=0;
int find=0;
while(find<nums.length){
if(nums[find]!=0){
int temp=nums[behind];
nums[behind]=nums[find];
nums[find]=temp;
behind++;
}
find++;
}
}

8512

被折叠的 条评论
为什么被折叠?



