Leecode热题100---283:移动零

**题目:**给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。

C++:
1、常规思路:
先遍历一次,记录当前遍历到的非零元素的个数(若为第n个非0的元素,就将该非零至于数组中下标为n - 1的位置);在非零元素遍历完毕后,得到flag个非零元素。从第flag + 1个元素开始,剩余的元素全部置0,即为所求结果。

#include<iostream>
#include<vector>
using namespace std;

class Solution
{
public:
	void zero(vector<int>& nums)
	{
		int n = 0;
		for (int i = 0; i < nums.size() - 1; i++)
		{
			if (nums[i] != 0)    // 若不为零,则i和n-1交换
			{
				n++;
				nums[n - 1] = nums[i];
			}
		}
		if (n > 0)
		{
			for (int j = n; j < nums.size(); j++)
				nums[j] == 0;
		}
	}
};

int main()
{
	solution S;
	vector<int> nums = {2,5,8,0,1,6,0,7,0};
	S.zero(nums);
	return 0;
}

2、双指针
快慢指针,快指针向前移动,若不为0,则和慢指针交换,若为0,继续向前。

class solution
{
public:
	void zero(vector<int>& nums)
	{
		int n = nums.size(); int left = 0; int right = 0;
		while (right < n)
		{
			if (nums[right] != 0)
			{
				swap(nums[left], nums[right]);
				left++;
			}
			right++;
		}
	}
};

python:
思路:双指针
left指针指向非0的最后一位,right指向0的最后一位,每次判断right指向的是否为0,若为0则后移一位,若非0则交换left和right,让left向后移动一位。

from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]):
        n = len(nums)
        left = right = 0
        while right < n:
            if nums[right] != 0:
                temp = nums[right]
                nums[right] = nums[left]
                nums[left] = temp
                left += 1
            right += 1

if __name__== "__main__":
    nums = [0,1,0,3,12]
    res = Solution().moveZeroes(nums)
    print(nums)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ghx3110

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值