描述

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. PAT甲级题分类汇编——序言

    今天开个坑,分类整理PAT甲级题目(https://pintia.cn/problem-sets/994805342720868352/problems/type/7)中1051~1100部分.语言是 ...

  2. golang日志库之glog使用问题总结

    1. 日志默认输出路径为临时路径,可通过执行命令时带上 -log_dir="路径",指定输出,但路径必须已存在,源码如下,日志文件会生成两个 .INFO等后缀是符号链接文件,另一个 ...

  3. PB笔记之数据窗体分组合计列

  4. nfs挂载文件

    1. 安装必备插件  以防centos7默认没有启动nfs服务 yum -y install nfs-utils rpcbind # 启动 rpcbind 和配置开机自启动 systemctl sta ...

  5. 1.MVC基础-初识MVC,与WebForm比较

    1.Net WebForm的开发模式

  6. css 基础入门

    CSS 概述 为了让网页元素的样式更加丰富,也为了让网页的内容和样式能拆分开,css 由此而生,css 是 Cascading Style Sheets 的字母缩写,意思是层叠样式表,有了 css,h ...

  7. J.U.C之读写锁:ReentrantReadWriteLock

    此篇博客所有源码均来自JDK 1.8 重入锁ReentrantLock是排他锁,排他锁在同一时刻仅有一个线程可以进行访问,但是在大多数场景下,大部分时间都是提供读服务,而写服务占有的时间较少.然而读服 ...

  8. idea 实用插件

    尊重劳动成果,本插件的整理原文出自:https://blog.csdn.net/weixin_41846320/article/details/82697818,感谢老铁的辛苦原创. 插件安装方式: ...

  9. MongoDB官方推荐的GUI工具-Compass的使用

    探索和操作MongoDB数据的最简单方法 用于MongoDB的GUI.可视化地查看数据.以秒为单位运行临时查询.使用完整的CRUD功能与数据交互.查看和优化查询性能.可在Linux.Mac或Windo ...

  10. 什么是软件工具开发包(SDK)

    开发一个软件,需要经过编辑.编译.调试.运行几个过程. 编辑:使用编程语言编写程序代码的过程. 编译:将编写的程序进行翻译. 调试:程序不可能一次性编写成功,编写过程中难免会出现语法.语义上的错误,调 ...