【C++每日一练】双指针 力扣(202,283,1080)

力扣202 快乐数

#define  _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
    int bitSum(int n)//计算每一位的平方和函数
    {
        int sum = 0;
        while (n)
        {
            int t = n % 10;
            sum += t * t;
            n /= 10;
        }
        return sum;
    }
    bool isHappy(int n)
    {
        int fast = bitSum(n);//因为是快慢指针,判断条件又是fast!=slow,如果相等无法循环
        //所以赋值fast为slow的下一个数字,又因为在环内一定会相遇,所以不会死循环
        int slow = n;
        while (slow != fast)
        {
            slow = bitSum(slow);//模拟慢指针走一步的特征
            fast = bitSum(bitSum(fast));//模拟快指针走两步的特征
        }
        return slow == 1;//如果为1为true,不为1为falst;
    }
};

力扣283 移动零

#define  _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
    //[1,3,0,0,123,42,12,2,3]
    void moveZeroes(vector<int>& nums)
    {
        for (int dest = -1, cur = 0; cur < nums.size(); cur++)
        {
            if (nums[cur] != 0)//当cur不等于0时,将desc++与cur交换,使得desc位置的0不断后移,如同推箱子

            {
                dest++;
                swap(nums[cur], nums[dest]);
            }
        }
    }

力扣1080 复写0

#define  _CRT_SECURE_NO_WARNINGS

#include<iostream>
#include<vector>

using namespace std;


//因为从前向后遍历会覆盖数据,所以这道题需要从后向前赋值
class Solution {
public:
    void duplicateZeros(vector<int>& arr)
    {
        int cur = 0, desc = -1;//定义指针,从前向后遍历,确认cur最终位置
        int n = arr.size();
        while (cur < n) {
            if (arr[cur]) {
                desc++;
            }
            else {
                desc += 2;
            }
            if (desc >= n - 1)//如果desc==n或者大于n,证明越界.立刻终止循环
                break;
            cur++;
        }


        if (desc == n)//desc只有等于零的结果
        {
            arr[n - 1] = 0;//修正复写
            cur--; desc -= 2;//修正指针
        }
        while (cur >= 0)//正常循环,如果cur为1正常复制
        {
            if (arr[cur])
                arr[desc--] = arr[cur--];
            else//如果为零,desc赋值0,cur正常减
            {
                arr[desc--] = 0;
                arr[desc--] = 0;
                cur--;
            }
        }

    }
};
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值