每日一题-数组 leetcode283

160 阅读1分钟

一、题目描述

二、提交代码

class Solution {
    public void moveZeroes(int[] nums) {
        for(int i =0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i] ==0 && nums[j]!=0){
                    swap(nums,i,j);
                    i++;
                    break;
                }
            }
        }
    }
    public int[] swap(int[] nums,int a,int b){
        int temp =nums[a];
        nums[a] =nums[b];
        nums[b] = temp;
        return nums;
    }
}

三、提交代码思路

双指针,外圈for循环事先寻找0元素,内圈for循环负责寻找首个非0元素,找到后进行元素位置互换,外圈for循环确保了慢指针走过的位置皆为非0元素

四、优解代码

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

五、优解思路

逆向思维,题目需要将0元素移动到数组末尾,即将数组中的非0元素移至数组前端

六、优解特点

不占用多余的内存空间,且只遍历一次数组