【LeetCode】283. Move Zeroes
2016-01-07 13:16
274 查看
Problem
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.
Analyze
假设给你开一个辅助数组,你会怎么做?——把非0的元素放到辅助数组中,略过0元素,最后在辅助数组末端添加足够的0即可。
时间复杂度O(n)。
不开辅助数组呢?
——其实还是一样,只不过原数组的空间可以复用。当没有0时,自然无须移动,当至少出现一个0时,当前待移动的非0元素前面必然至少有一个空闲位置可以使用(0位视为空闲)。
My code
class Solution { public: void moveZeroes(vector<int>& nums) { vector<int>::iterator pos = nums.begin(); for (vector<int>::iterator num = nums.begin(); num != nums.end(); num++) { if ((*num)) { if (num != pos) (*pos) = (*num); pos++; } } for (; pos != nums.end(); pos++ ) (*pos) = 0; } };
相关文章推荐
- vs 打印信息到Output
- java怎么连接sql server,需要注意的几点
- Javascript面向对象编程(一):封装
- maven使用实例记录
- Python Web 实现Ajax调用
- Objective-C点语法
- HTML <fieldset> 标签的使用
- IOS object-c 中定时器NSTimer的开启与关闭
- POJ 1426-Find The Multiple
- wampserver部署笔记 设置apache使得外网可以访问
- Android 第三方开源 SlidingMenu 使用详解
- Objective-C点语法
- 第1章第1节练习题5 无序表删除指定区间值
- 大排量 下次换车,一定要大排量
- 一个防止误删MSSQL数据库的方法
- iOS下 UILabel 如何自动换行
- 20160107 textfield 的 汉字的限制
- XML Schema基本结构
- js根据浏览器窗口大小实时改变网页文字大小
- maven概念