283.移动零

283.移动零,第1张

LeetCode链接:283. 移动零 - 力扣(LeetCode)

思路一:利用双指针,指针i和指针j都指向索引0,遍历数组,当遇到非0的元素时,将array[j]存入到array[i++]中,最后再遍历[i,array.length]并赋值为0

java代码:

class solution{
    public void moveZeroes(int[] nums){
        if(nums == null) return;
        int n = nums.length;
        int i = 0;
        
        for(int j = 0; j < n; j++){
            if(nums[j] != 0){
                nums[i++] = nums[j];
            }
        }

        for(int j = i; j < n; j++){
            nums[j] = 0;
        }
        
    }
}

思路二:指针i和指针j指向索引0,遍历数组,当遇到array[j] != 0时候交换指针i和指针j所在的位  置,并使i++

java代码:

class solution{
    public void moveZero(int[] nums){
        if(nums == null) return;
        int n = nums.length;
        int i = 0;
        
        for(int j = 0; j < n; j++){
            if(nums[j] != 0){
                int temp = nums[j]
                nums[j] = nums[i];
                nums[i++] = temp;
                
            }
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1330216.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存