leetcode - Move Zeroes
2015-10-06 16:33
218 查看
leetcode - Move Zeroes
Given an array
For example, given
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
思路:先把非零的数排到前面,并记录非零数最后的位置,然后把后面的其他数字都设置为0即可。
时间复杂度O(n), 空间复杂度 O(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,
numsshould 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.
class Solution { public: void moveZeroes(vector<int>& nums) { int pos = -1, i = 0; while(i<nums.size()){ if(nums[i] != 0){ nums[++pos] = nums[i]; } i++; } while(pos+1<nums.size()){ nums[++pos]=0; } } };
思路:先把非零的数排到前面,并记录非零数最后的位置,然后把后面的其他数字都设置为0即可。
时间复杂度O(n), 空间复杂度 O(1)
相关文章推荐
- Thinkphp 动态查询 getBy 与 getFieldBy
- MacOSX Cocos2d-x 配置Android Studio以及Xcode开发环境
- Java实现循环单链表……
- 斐波那契的递归函数
- C语言设计模式与接口
- POJ2502 Subway 最短路
- 安全技术目标
- java并发之ConcurrentHashMap
- 找出有环链表中环的起点
- java线程详解(三)
- 线就是思路、方法、绳子 连成成品才有价值
- [Training Video - 3] [Groovy in Detail] Non-static and Static variables, objects and object referances
- JSP要点总结
- 1002. A+B for Polynomials (25)
- 用快排思路解决逆序对问题
- IOS开发UI进阶之UITableView三
- 基于TCP网络通信的简易多线程GUI聊天室
- poj_2486 动态规划
- SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
- 纪念碑