移动零(数组)

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:

输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

示例 2:

输入: nums = [0]
输出: [0]

提示:

1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31- 1

解题思路:

1.非零往前挪

index表示0位置,i一直后移,如果碰到非零元素,将该元素赋给前一个0的位置,然后index后移一位,注意:index++,表示先赋值再++。最后index会停留在所有非零元素移动后第一个0所在的位置,将其后面的值都赋0。

class Solution {
    
    
    public void moveZeroes(int[] nums) {
    
    
        if(nums.length==0||nums==null){
    
    
            return;
        }
        int index=0;
        //把非零往前挪
        for(int i=0;i<nums.length;i++){
    
    
            if(nums[i]!=0){
    
    
                nums[index++]=nums[i];
            }
        }
        //后面都是零
        while(index<nums.length){
    
    
            nums[index]=0;
            index++;
        }
    }
}

2.双指针

i表示统计0的个数,j一直后移,j-i为前面第一个0的位置,j 指针和 i 指针交换。注意:如果数组中只有一位数字且为1,还要判断如果一个0都没有,不用交换。

class Solution {
    
    
    public void moveZeroes(int[] nums) {
    
    
        int i=0;
        for(int j=0;j<nums.length;j++){
    
    
            if(nums[j]==0){
    
    
                i++;  
            }
            else if(i!=0){
    
    
                nums[j-i]=nums[j];
                nums[j]=0;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/creazypeople/article/details/129981854