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.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void movevector(vector<int>& data);
int main()
{
	vector<int>data = { 0, 1, 1,0,0, 3, 2, 0, 6,0 };
	movevector(data);
	for (auto i : data)
	{
		cout << i << ' ';
	}
	system("pause");
	return 0;
}

void movevector(vector<int>&data)
{
	//相当于removeelment 吧0的移出去得到非0的长度 最后添加上去0就行了
	//int index = 0;
	//for (int i = 0; i < data.size(); i++)
	//{
	//	if (data[i])
	//		data[index++] = data[i];
	//}//index表非0的个数
	//for (int i = index ; i < data.size(); i++)
	//	data[i] = 0;

	//第二种 弄两个指针i,j,,,用i表示非0的数的地址,j表示0的地址,这样交换二者值
	int j = 0;
	for (int i = 0; i < data.size(); i++)
	{
		if (data[i])
		{
			swap(data[i], data[j++]);
		}
	}
	//如果没0则i 和j 是同时增加,当遇到0时,i增,j不变指的是0,
}


你可能感兴趣的:(Move Zeroes)