【双指针】【数之和】 LeetCode 633.平方数之和

算法思想:

  • 双指针枚举i,j;类似三数之和
cpp 复制代码
class Solution {
public:
    bool judgeSquareSum(int c) {
        long long  sum=0;
        vector<int> dp;dp.push_back(0);
        long long start=1;
        while(sum < c)
        {
            sum = start *start;
            if(sum>c) break;
            else dp.push_back(sum);
            start++;

        }
        long long l=0,r=dp.size()-1;
        while(l<=r)
        {
            //long long tmp =dp[l] + dp[r]; 会溢出
            if(dp[l] < c-dp[r])
            {
                l++;
                continue;
            }
            else if (dp[l] > c - dp[r])
            {
                r--;
                continue;
            }
            else if(dp[l] == c-dp[r]) return true;
        }
        return false;

    }
};

但注意一点,dpl + dpr会溢出,所以用减法不会溢出;

相关推荐
武子康3 小时前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法
卡尔曼的BD SLAMer3 小时前
北斗导航 |GNSS ION论文集汇总1997到2022(链接在文末)
算法·北斗导航
时间的拾荒人3 小时前
Redis Cluster 集群详解:分片算法、搭建、故障处理与扩容实战
数据库·redis·算法·集群
老师我太想进步了20265 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
kyle~6 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
Pniubi7 小时前
贪心算法入门
算法·贪心算法
MobotStone8 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
复杂网络与机器学习8 小时前
Meta 重写 K-Means:25 轮压成 2 轮,GPU 快 45 倍
人工智能·算法·数据挖掘
lunar_coder8 小时前
【算法】前缀和:把 O(n) 的重复劳动变成 O(1) 的一次查询
c++·算法
Pniubi9 小时前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展