Leetcode 283. Move Zeroes

283. Move Zeroes

 

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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.


思路:遍历向量数组,如果遇到0就删除,然后在末尾插入。

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;

/***********************************提交部分*********************************/ 
class Solution
{
	public:
		void moveZeroes(vector<int>& nums)
		{
			vector<int>::iterator p=nums.begin();
			int i=1,n=nums.size();
			while(i<=n)
			{
				if(*p==0)
				{
					vector<int>::iterator p1=p;
					p=nums.erase(p1);
					nums.push_back(0);
				}

				else
					p++;
				++i;
			}
		}
};
/*******************************************************************************/

int main()
{
	int n;
	scanf("%d",&n);
	vector<int> a;
	int tmp;
	for(int i=0; i<n; i++)
	{
		scanf("%d",&tmp);
		a.push_back(tmp);
	}
	Solution s;
	s.moveZeroes(a);
	for(int i=0; i<n; i++)
		printf("%d ",a[i]);
	return 0;
}


做这题的时候主要是卡在erase函数的应用,因为平时少用,所以不是很熟悉。现在可以总结几个点:
1.要注意erase函数的形参是一个迭代器,指向要删除的元素,操作成功后返回的也是一个迭代器,指向已删除元素的下一个元素。
2. 循环的条件不能写成for(p=nums.begin(); p!=nums.end(); p++); 原因有二,一是当把所有的0都放到vector后面之后,会陷入死循环;
二是因为如果没有重新定义一个迭代器p1就直接进行erase(p); 操作,p就会成为野指针,p++这步就无法执行,所以必须要重新定义一个迭代器,
且把p赋值为erase(p1),相当于p++,就不用再画蛇添足多写一句p++了。
3. 注意定义迭代器的语法vector<int>::iterator p1,不能写成int *p1,亲测有效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值