leecode 解题总结:283. Move Zeroes

本文介绍了一种将数组中所有零元素移动到末尾同时保持非零元素相对顺序的算法。通过从数组尾部开始遍历,每遇到一个零元素便将其与最后一个非零元素交换位置,最终实现零元素的归位。此方法不使用额外空间,且减少了操作次数。
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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.

分析:从后向前,每次找到0,然后就将其后面部分每个元素都前移一位,将该0放到最后位置。
这样带来的问题是最前面的0被移动到最后,也可以,也就是所有0的位置是逆置的,然后最后把
0的部分逆置一下即可。输出0的总个数num,则从n-1~n-num处的0逆置一下
如果从前向后,每次找到0,就把该0移动到最后,这样是可以的,
时间复杂度:O(n^2)

输入:
5
0 1 0 3 12
1
1
1
0
2
0 0
输出:
1 3 12 0 0
1
0
0 0

关键:
1 从后向前,每次找到0,然后就将其后面部分每个元素都前移一位,将该0放到最后位置。
这样带来的问题是最前面的0被移动到最后,也可以,也就是所有0的位置是逆置的,然后最后把
0的部分逆置一下即可。输出0的总个数num,则从n-1~n-num处的0逆置一下
*/

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        //从后向前,每次找到0,就将后面部分前移一位
		if(nums.empty())
		{
			return;
		}
		int count = 0;
		int size = nums.size();
		for(int i = size - 1 ; i >= 0 ; i--)
		{
			if(0 == nums.at(i))
			{
				count++;
				//开始移动位置: i+1~size-1都向前移动
				for(int j = i + 1 ; j <= size - 1 ; j++)
				{
					nums.at(j-1) = nums.at(j);
				}
				//将0放在最后
				nums.at(size - 1) = 0;
			}
		}
		//接下来就是逆置最后的0,
		reverse(nums.begin() + size - count , nums.end());
    }
};

void print(vector<int>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	for(int i = 0 ; i < size ; i++)
	{
		cout << result.at(i) << " " ;
	}
	cout << endl;
}

void process()
{
	 vector<int> nums;
	 int value;
	 int num;
	 Solution solution;
	 vector<int> result;
	 while(cin >> num )
	 {
		 nums.clear();
		 for(int i = 0 ; i < num ; i++)
		 {
			 cin >> value;
			 nums.push_back(value);
		 }
		 solution.moveZeroes(nums);
		 print(nums);
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值