283. 移动零 MoveZeros

2020-11-07  本文已影响0人  滨岩

方法一: 将非0元素单独存储在一个列表中

//时间复杂度O(n)
//空间复杂度O(n)
    public void moveZeroes(int[] nums) {

        List<Integer> nozeroList=new ArrayList<Integer>(nums.length);
        for(int i=0;i<nums.length;i++){
            if(nums[i]==0){
                continue;
            }
            nozeroList.add(nums[i]);
        }

        for(int i=0;i<nozeroList.size();i++){
            nums[i]=nozeroList.get(i);
        }

        for(int i=nozeroList.size();i<nums.length;i++){
            nums[i]=0;
        }

    }

方法2:利用双指针法

image.png image.png

noZeroIndex-[0..noZeroIndex)中保存所有当前遍历过的非0元素

image.png image.png
image.png image.png
//时间复杂度O(n)
//空间复杂度O(1)
    public void moveZeroes(int[] nums) {

        //[0...noZeroIndex)  nums中 0--noZeroIndex  均为非0元素
        int noZeroIndex=0;
        //遍历到第i个元素后,保证[0...i]中的所有非0元素
        //都按照顺序排列在[0...k)
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                nums[noZeroIndex++]=nums[i];
            }
        }

        //将nums中剩余的位置放置为0
        for(int i=noZeroIndex;i<nums.length;i++){
            nums[i]=0;
        }

    }

方法3:双指针-直接交换

image.png image.png image.png image.png
    //时间复杂度O(n)
    //空间复杂度O(1)
    public void moveZeroes(int[] nums) {

        //[0...noZeroIndex)  nums中 0--noZeroIndex  均为非0元素
        int noZeroIndex=0;
        //遍历到第i个元素后,保证[0...i]中的所有非0元素
        //都按照顺序排列在[0...k)
        //同时保证 [k..i] 都是零元素
        for(int i=0;i<nums.length;i++){
            if(nums[i]==0){
                continue;
            }
            //每个元素都不相等 就不用切换
            if(i!=noZeroIndex){
                swap(nums,noZeroIndex,i);
            }

            noZeroIndex++;
        }
    }


    private void swap(int[] nums,int source,int target){
        int temp=nums[source];
        nums[source]=nums[target];
        nums[target]=temp;
    }
上一篇 下一篇

猜你喜欢

热点阅读