move-zeroes

题目内容

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

解题思路

1.设置两个指针,都指向数组的第0个位置;
2.右指针每次向右移动一位,遇到非0则与左指针的数指进行交换,如果数组的nums[0]为非0,第一次是不会有交换的。

代码

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size(), left = 0, right = 0;
        while (right < n) {
            if (nums[right]) {
                swap(nums[left], nums[right]);
                left++;
            }
            right++;
        }
    }
};

相关文章:

  • 2021-04-24
  • 2021-11-16
  • 2021-06-04
  • 2021-07-01
  • 2021-09-22
  • 2021-06-26
  • 2021-08-26
猜你喜欢
  • 2021-07-24
  • 2021-11-24
  • 2021-05-02
  • 2021-07-14
相关资源
相似解决方案