LeetCode 283——Move Zeroes

https://blog.csdn.net/CrazyOnes/article/details/88149530 

今天问马哥在学啥,他直接给我一个这个。我研究一下午,最后还是gg。。看了题解恍然大悟,这里简单记录一下,完整版请参考链接


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.

Example:

Input:[0,1,0,3,12]

Output:[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.
 


我最开始的想法是:

1.找到一共有多少个0,然后集体移动。(思路不对)

2.直接把数组转成int,然后再做。([1,0,12,0,4]这个数组,有12这种数字,只能用str拼接,但是如果数组很大,这个消耗也是O(2n),还是挺大的,不过也算是个想法吧)


标准解法:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size();
        int firstZero = 0;
        for(int i=0;i<n;++i){
            //如果这个值不为0,则交换。当然有的地方是自己换自己,但是不会带来问题。
            if(nums[i]!=0){
            int tmp = nums[i];
            nums[i] = nums[firstZero];
            nums[firstZero++] = tmp;//firstZero别忘了++   
            } 
        }     
    }
};

two pointer的思想,这个直接交换(有时候是自己换自己的操作我确实没有想到)这里有点东西。
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值