描述

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.

分析

遍历这个数组,判断当前元素是否为0,如果为0,就把0删除(erase),并且将0放到(push_back)最后。否则,将迭代器指向后一元素。

考虑到erase操作会使迭代器失效,因此让该函数返回一个迭代器,这样,执行删除元素的操作后,迭代器会自动指向被删除元素的后一元素(相当于把迭代器加1)。

对于把0压到数组末尾的操作,也会带来新的问题:数组的末尾元素不断更新,可能会导致迭代器永远到不了末尾。

为此,需要记录初始状态下数组的尾迭代器,然后在循环体里判断迭代器是否已到了这个尾迭代器,如果到了,直接break。

于是就有了下面的代码:


class Solution {
public:
void moveZeroes(vector<int>& nums) {
auto e = nums.end(); //保存初始状态下数组的尾迭代器
for(auto it = nums.begin(); it != nums.end();){
if(it != e){ //如果还没到达末尾
if(*it == 0){ //判断是否为0
it = nums.erase(it); //删除操作会更新当前的迭代器
nums.push_back(0); //push操作会改变末尾元素
}else //如果不为0,就让迭代器指向下一元素
++it;
}else //如果已到达初始状态下的末尾,就退出,避免进入死循环
break;
}
}
};

然而这段代码还是提示超时了。。。

看来还是naive啊,估计还是尾后迭代器失效,造成了一个死循环(不断地在删除0,又不断地把0添加到末尾,迭代器永远到不了最后)

机智如我,换成用int型变量判断是否到达末尾:

class Solution {
public:
void moveZeroes(vector<int>& nums) {
int i = 0;
for(auto it = nums.begin(); it != nums.end();){
if(i != nums.size()){
if(*it == 0){
it = nums.erase(it);
nums.push_back(0);
}else
++it;
}else
break;
++i;
}
}
};

果然ac了。。。

心得

用迭代器遍历vector时,对于会更新、破坏迭代器的操作,一定要慎之又慎啊。

leetcode解题报告(16):Move Zeroes的更多相关文章

  1. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  2. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  3. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  4. LeetCode解题报告汇总! All in One!

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 把自己刷过的所有题目做一个整理,并且用简洁的语言概括了一下思路,汇总成了一个表格. 题目 ...

  5. LeetCode Javascript实现 283. Move Zeroes 349. Intersection of Two Arrays 237. Delete Node in a Linked List

    283. Move Zeroes var moveZeroes = function(nums) { var num1=0,num2=1; while(num1!=num2){ nums.forEac ...

  6. LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors

    1. Rotate List Given a list, rotate the list to the right by k places, where k is non-negative. Exam ...

  7. leetCode解题报告5道题(六)

    题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...

  8. LeetCode解题报告—— 2 Keys Keyboard & Longest Palindromic Substring & ZigZag Conversion

    1. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You ...

  9. leetCode解题报告5道题(九)

    题目一:Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ...

随机推荐

  1. mininet安装配置

    mininet安装配置 安装mininet mininet使用 在VM中运行mininet 安装VMware,在VMware中打开下载好的mininet虚拟机映像 启动虚拟机,虚拟机的初始账号密码均为 ...

  2. vsCode 代码不高亮显示的问题——安装Vetur插件

    vsCode 代码不高亮显示: 解决办法:安装Vetur插件 点击左侧菜单的扩展-->搜索Vetur-->点击安装-->安装完成重启vsCode

  3. VS.NET(C#)--2.1认识控件

    Web控件 四种控件 1.HTML控件 2.HTML服务器控件    在服务器端执行 3.ASP.NET服务器控件   在服务器端执行 4.用户控件和自定义控件  用户自定义控件在服务器端执行 注意: ...

  4. winform 替换word文档中的字段(包含图片添加),生成导出PDF文件(也可是word文件)

    1.先打开你需要替换的word文档,在想要后续更换字段值的地方添加“书签”. 2.将模板文档存放在 程序的Debug文件下. 3.生成文件的按钮点击事件 代码: string templatePath ...

  5. table固定宽度与自动宽度

    table-layout:auto(创建的table默认是此布局模式): 对table和td.th指定的宽度无效,浏览器会计算所有单元格的内容宽度才能得出一列宽度 如果想对单元格的内容自动折行需使用w ...

  6. CSS_引入方式

    一 CSS的引入方式 CSS是Cascading Style Sheets的简称,中文称为层叠样式表,用来控制网页数据的表现,可以使网页的表现与数据内容分离       1.行内式           ...

  7. iOS 数据源切换混乱问题

    问题场景 这个问题遇到是偶然的,正常来说是不会出现的.但是有时候在一些极端操作情况下,还是出现了. 现在我说明下这个场景.页面上是一个tableview,那对应的有一个dataSource,页面顶部有 ...

  8. layui表单

    {include file="Public:inner_header" /} <link rel="stylesheet" href="__ST ...

  9. LVS实现健康性检查功能

    LVS高可用性 Director不可用,整个系统将不可用:SPoF Single Point of Failure 解决方案:高可用 keepalived heartbeat/corosync 某RS ...

  10. javascript reduce 前端交互 总计

    sum(){ return this.products.reduce((total,next)=>{ return total + next.price * next.aumout},0) } ...