移动0 - 简单

*************

C++

topic:283. 移动零 - 力扣(LeetCode)

*************

Hello, how's your weekend.

during my learning, topic about array perplex me. Just do it.

Inspect the topic:

It is a easy one but not easy for me now because I have no idea anout the pointer.

When talks about sort, use SORT standard library always fine. However this topic, sort doesnot work.

Doble pointer maybe works. nums[j] = nums[i] if nums[i] != 0. Double pointer do work. Make two pointer, pointer i moves faster and pointer j moves slower. And pointer i & pointer j works in the same array.

Then the code is as follow

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        
        int n = nums.size(); // get the length
        int j = 0;

        for(int i = 0; i < n; i++){
            if (nums[i] != 0){
                nums[j] = nums[i];
                j++;
            }
        }
    }
};

however this code doesnot works, seeing the result:

seeing the result cannot understood, just hand write the running progress:

nums = 0 1 0 3 2

  • i = 0, nums[0] == 0, j = 0, nums = 0 1 0 3 2
  • i = 1, nums[1] = 1, nums[0] = 1, j = 1, nums = 1 1 0 3 2
  • i = 2, nums[2] == 0, j = 1, nums = 1 1 0 3 2
  • i = 3, nums[3] = 3, j = 1, nums[1] = nums[3] = 3, j = 2, nums = 1 3 0 3 2
  • i = 4, nums[4] = 2, j = 2, nums[2] = nums[4] = 2, nums = 1 3 2 3 2

So after moving pointer j,  make sure that nums[j + 1]  ~ nums[n - 1] == 0;

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        
        int n = nums.size(); // get the length
        int j = 0;

        for(int i = 0; i < n; i++){
            if (nums[i] != 0){
                nums[j] = nums[i];
                j++;
            }
        }

        for(int i = j; i < n; i++){
            nums[i] = 0;
        }
    }
};

For easy use, introduce a standard library SWAP. The usage of swap is to xechange two viraties position

#include <utility> // 包含swap函数的头文件

int a = 10;
int b = 20;
std::swap(a, b); // 交换a和b的值

then the code can be more concise

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int j = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] != 0) {
                swap(nums[i], nums[j]);
                j++;
            }
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值