美文网首页
leetcode283.移动零

leetcode283.移动零

作者: 憨憨二师兄 | 来源:发表于2020-04-09 12:05 被阅读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;
                }
            }
        }
    }
    

    执行结果:


    相关文章

      网友评论

          本文标题:leetcode283.移动零

          本文链接:https://www.haomeiwen.com/subject/zviqmhtx.html