LeetCode 283 移动零 题解

LeetCode 283 移动零 题解

  • 方法1 双指针
  • 方法2 快排思想

LeetCode链接

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

方法1 双指针

自己写的这个双指针的竟然还挺官方哈哈哈

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null || nums.length == 0){
            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;
        }
        return ;
    }
}

方法2 快排思想

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null || nums.length == 0){
            return ;
        }
        for(int i = 0,j = 0; i < nums.length;++i){
            if(nums[i] != 0){
                if(i>j){//避免i==j时(也就是开头全是非零元素)也进行交换
                nums[j] = nums[i];
                nums[i] = 0;
                }
                j++;//一定要在这里j++,不然开头全是非零元素时,j无法越过该元素
            }
        }
        return ;
    }
}

你可能感兴趣的:(Java,LeetCode刷题记录,leetcode,java,算法)