[LeetCode] 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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

解题思路

用两个指针i,j分别指向0和非零,当j指向非零时,交换两个指针所指向的元素,并且i向前走一步;j则每次循环无论是否交换都向前走一步。

实现代码

C++:

// Runtime: 20 ms
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int i = 0;
        int j = 0;
        while (j < nums.size())
        {
            if (nums[j] != 0)
            {
                swap(nums[i], nums[j]);
                i++;
            }
            j++;
        }
    }
};

Java:

// Runtime: 1 ms
public class Solution {
    public void moveZeroes(int[] nums) {
        int i = 0;
        int j = 0;
        while (j < nums.length) {
            if (nums[j] != 0) {
                if (j != i) {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
                i++;
            }
            j++;
        }
    }
}
目录
相关文章
|
算法 Python
LeetCode 283. 移动零 Move Zeroes
LeetCode 283. 移动零 Move Zeroes
LeetCode 283. Move Zeroes
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
64 0
LeetCode 283. Move Zeroes
|
存储 索引
LeetCode 73. Set Matrix Zeroes
给定一个m * n 的矩阵,如果当前元是0,则把此元素所在的行,列全部置为0. 额外要求:是否可以做到空间复杂度O(1)?
78 0
LeetCode 73. Set Matrix Zeroes
LeetCode之Move Zeroes
LeetCode之Move Zeroes
82 0
|
索引 Python Java
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] 说明: 必须在原数组上操作,不能拷贝额外的数组。
745 0
|
C++ Java 存储
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。
1053 0
LeetCode 172 Factorial Trailing Zeroes(阶乘后的零)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50568854 翻译 给定一个整型n,返回n!后面的零的个数。
598 0
LeetCode 283 Move Zeroes(移动所有的零元素)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50409676 翻译 给定一个数字数组,写一个方法将所有的“0”移动到数组尾部,同时保持其余非零元素的相对位置不变。
681 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.
763 0