[LeetCode]--283. Move Zeroes

简介: 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.For example, given nums = [0, 1, 0, 3, 12], after call

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

我想着先不是零的都移到前面,然后后面的补零。

public void moveZeroes(int[] nums) {
        int j = 0;
        for (int i = 0; i < nums.length; i++)
            if (nums[i] != 0)
                nums[j++] = nums[i];
        while (j < nums.length)
            nums[j++] = 0;
    }
AI 代码解读

另外一种,边移边补零。

public void moveZeroes(int[] nums) {
        int i = 0;
        int j = 0;
        while (j < nums.length) {
            if (nums[j] != 0) {
                if (j != i) {
                    nums[i++] = nums[j];
                    nums[j] = 0;
                } else
                    ++i;
            }
            ++j;
        }
    }
AI 代码解读
yexx
+关注
目录
打赏
0
0
0
0
42
分享
相关文章
LeetCode 283. Move Zeroes
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
195 0
LeetCode 283. Move Zeroes
LeetCode 73. Set Matrix Zeroes
给定一个m * n 的矩阵,如果当前元是0,则把此元素所在的行,列全部置为0. 额外要求:是否可以做到空间复杂度O(1)?
193 0
LeetCode 73. Set Matrix Zeroes
LeetCode之Move Zeroes
LeetCode之Move Zeroes
121 0
LeetCode 283:移动零 Move Zeroes
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 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,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。
790 0
LeetCode 73 Set Matrix Zeroes(设矩阵元素为0)(Array)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/52139263 翻译 给定一个mm x nn的矩阵matrix,如果其中一个元素为0,那么将其所在的行和列的元素统统设为0。
1136 0
LeetCode 172 Factorial Trailing Zeroes(阶乘后的零)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50568854 翻译 给定一个整型n,返回n!后面的零的个数。
637 0
LeetCode 283 Move Zeroes(移动所有的零元素)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50409676 翻译 给定一个数字数组,写一个方法将所有的“0”移动到数组尾部,同时保持其余非零元素的相对位置不变。
728 0
leetcode Set Matrix Zeroes
Question Given a m x n matrix, if an element is 0, set its entire row and column to 0.
808 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问