LeetCode Move Zeroes (简单题)

本文介绍了一种算法,用于将整型数组中的所有零元素移至数组末尾,同时保持非零元素的相对顺序不变。提供了两种实现方式,一种使用C++,另一种使用Python。这两种方法都有效地解决了问题,并附带了AC代码。

 

 

 

题意:

  给定一个整型数组nums,要求将其中所有的0移动到末尾,并维护所有非0整数的相对位置不变。

 

思路:

  扫一遍,两个指针维护0与非0的交界,将非0的数向前赋值就行了。

 

C++ 

 1 class Solution {
 2 public:
 3     void moveZeroes(vector<int>& nums) {
 4         int idx=0;
 5         for(int i=0; i<nums.size(); i++)
 6             if(nums[i]!=0)
 7                 nums[idx++]=nums[i];
 8         while(idx<nums.size())
 9             nums[idx++]=0;
10     }
11 };
AC代码

 

python3

1 class Solution(object):
2     def moveZeroes(self, nums):
3         """
4         :type nums: List[int]
5         :rtype: void Do not return anything, modify nums in-place instead.
6         """
7         nums.sort(key=lambda x:0 if x==0 else -1 )
AC代码

 

 1 class Solution(object):
 2     def moveZeroes(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         cnt=nums.count(0)
 8         for i in range(cnt):
 9             nums.remove(0)
10             nums.append(0)
AC代码

 

转载于:https://www.cnblogs.com/xcw0754/p/4916801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值