283. Move Zeroes

1.描述

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.

2.分析

3.代码

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int pos = 0, cur = 0, n = nums.size() - 1;
        while (cur <= n) {
            nums[cur] == 0 ? cur++ : (nums[pos++] = nums[cur++]);
        }
        
        while (pos <= n) nums[pos++] = 0;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 1 宋初的姐姐要结婚了,姐姐说姐夫眼光太差,硬要拉着宋初去当个电灯泡。毕竟是姐姐一生最幸福的时刻,宋初还是去了。 ...
    大芝呀阅读 683评论 0 0
  • 很多人说改变难,主要是知易行难。人改变有六个阶段:1不知不觉,2知而不动,3知而心动,4知而行动,5动而坚持,6修...
    Lily_a6cc阅读 220评论 2 0
  • 庭院深 高墙困 又何如 吾亦感暗香浮动 吾亦可乐在其中 自得一方静
    所欲为何阅读 248评论 1 8
  • 我从雪的缝隙看六月的海 你眯眼笑笑,重叠的爱情无视一片蔚蓝 光透过云的白,我透过红色的信笺 这个季节和那个季节重逢...
    当代诗人云烟阅读 335评论 8 13