描述

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. Istio技术与实践6:Istio如何为服务提供安全防护能力

    凡是产生连接关系,就必定带来安全问题,人类社会如此,服务网格世界,亦是如此. 今天,我们就来谈谈Istio第二主打功能---保护服务. 那么,便引出3个问题: l  Istio凭什么保护服务? l  ...

  2. IO是否会一直占用CPU?(转)

    原文来自知乎:https://www.zhihu.com/question/27734728 这是一个很好的关于并发/并行系统的问题.简单回答就是:IO所需要的CPU资源非常少.大部分工作是分派给DM ...

  3. Markdown试试

    from os import time print("haha") from os import time print("haha") time.time()! ...

  4. mac下卸载android studio

    Execute these commands from the terminal rm -Rf /Applications/Android\ Studio.app rm -Rf ~/Library/P ...

  5. TCP与UDP协议必知必会

    TCP协议 一个工作在传输层的传输控制协议,面向连接.可靠的流式协议,HTTP协议建立在TCP基础上.每个TCP报文,实际在网络层进行封装成IP数据报,会进行IP分片(受限于MTU). 头部(20字节 ...

  6. zookeeper安装简要步骤

    vi zoo.cfg1.dataDir=/var/zookeeper2.server.1=zoo1:2888:3888server.2=zoo2:2888:3888server.3=zoo3:2888 ...

  7. vbox 网络配置

    vagrant主机与虚拟机通讯网络有两种模式: config.vm.network "private_network", ip: "192.168.33.10" ...

  8. docker 推送镜像到阿里云

    1. 登录阿里云Docker Registry $ sudo docker login --username=www.18860363800@hotmail.com registry.cn-beiji ...

  9. KeepAlive细谈

    来自: http://blog.sina.com.cn/s/blog_e59371cc0102ux5w.html 最近工作中遇到一个问题,想把它记录下来,场景是这样的: 从上图可以看出,用户通过Cli ...

  10. nginx实现fastcgi反向代理

    实现FastCGI: CGI的由来:最早的Web服务器只能简单地响应浏览器发来的HTTP请求,并将存储在服务器上的HTML文件返回给浏览器,也就是静态html文件,但是后期随着网站功能增多网站开发也越 ...