您的位置:首页 > 其它

283. Move Zeroes

2015-12-20 00:30 316 查看
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.
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时报错了,显示没有该成员!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: