leetcode283.移动零

2020-04-09  本文已影响0人  憨憨二师兄

题目链接
题解:
思路一:交换

class Solution {
    public void moveZeroes(int[] nums) {
        int firstZero = 0;
        boolean isMatchZero = false;
    
        for(int i = 0;i < nums.length;i++){
            if(!isMatchZero && nums[i] == 0){
                firstZero = i;
                isMatchZero = true;
            }
            if(nums[i] != 0){
                swap(nums,i,firstZero);
                firstZero++;
            }
        }
    }

    public static void swap(int[] arr,int i,int j){
        if(arr[i] == arr[j]){
            return;
        }
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }
}

执行结果:



思路二:覆盖

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

执行结果:


思路三:滚雪球

class Solution {
    public void moveZeroes(int[] nums) {
        snowBall(nums);
    }
    private void snowBall(int[] nums){
        int ballSize = 0;
        for(int i = 0;i < nums.length;i++){
            if(nums[i] == 0){
                ballSize++;
            }
            if(nums[i] != 0 && ballSize > 0){
                nums[i - ballSize] = nums[i];
                nums[i] = 0;
            }
        }
    }
}

执行结果:


上一篇下一篇

猜你喜欢

热点阅读