LeetCode笔记:283. Move Zeroes

版权声明:转载请注明出处。 https://blog.csdn.net/weixin_41657493/article/details/88034389

这是一道难度为Easy的问题,但不知道为什么,每次做我都会掉入思维误区,想出超级复杂的方案。今天整理一下,以便加深印象。

问题

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

分析

题目要求将数组中所有的0都移动到末尾,而其余元素保持原顺序。例如数组[0,1,0,3,12],操作后结果为[1,3,12,0,0]。要求原地执行,且操作次数尽量少。

思路

一个指针i向前遍历数组,一个指针j遇到0则停一次,每次循环j处元素都赋值为i处元素。也就是在0未出现时,数组保持不变,0出现1次,i处元素向前移动1位,0出现2次,i处元素向前移动2位,以此类推。知道i指针遍历结束,终止循环。此时自j指针开始直到数组末尾,都应该用0补位。

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

看到题目很容易往处理0的方向上思考,但这道题的解法妙就妙在处理非0,而不是处理0。提交上面的解法,会得到跑赢100%Java的提交的结果,真是生活中的小确幸。

猜你喜欢

转载自blog.csdn.net/weixin_41657493/article/details/88034389