283. Move Zeroes
2015-12-20 00:30
316 查看
Given an array
to the end of it while maintaining the relative order of the non-zero elements.
For example, given
be
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
*******动态数组的长度原来是用nums.size(),当用nums.length时报错了,显示没有该成员!!!
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 i=0,j=0; while(j<nums.size()) { if(nums[j]!=0) { if(i!=j) { nums[i]=nums[j]; nums[j]=0; } ++i; } ++j; } } };这题我最开始做的时候,我以为要将i循环到最后,结果出错了,显示time limited之类的。这就是我们编程习惯有问题,像我之前没有追求这种最优,其实程序能跑起来并且得到正确的结果就OK,也不注意时间和内存之类的。这题其实只要j循环到最后就行,因为这说明在j之前所有不为0的数该换到前面去的,已经都换到前面去了。。。到j等于最后一个元素的下标时,它前面的几个元素肯定都已经是0了(数组中存在一些0的情况下),这时i是跑不动最后的,而while循环会结束不了
*******动态数组的长度原来是用nums.size(),当用nums.length时报错了,显示没有该成员!!!
相关文章推荐
- 这次拖延更厉害了
- 这次拖延更厉害了
- webView(简单的浏览器)
- JAVA并发编程笔记四
- 设计师的名言
- uva 572 Oil Deposits
- find 命令
- 125 Valid Palindrome
- Window2003 iis+mysql+php+zend环境配置
- 初步认识Hive
- 第二次冲刺
- fibonacci数列C++语言多种实现
- 中奖概率算法(php 可用于刮刮卡,大转盘等抽奖算法)
- 走进全球互联网中枢,顶级域名服务器的分布
- MapReduce之Reduce端Join实现
- 各种基本排序算法总结
- iOS Default-568@2x.png启动图片设置问题
- 【Swift】通过tag删除动态创建的UIButton
- HTML 排版与标签(一)
- 接口的作用(C#)