【双指针】【数之和】 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会溢出,所以用减法不会溢出;

相关推荐
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
有点。8 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
周末也要写八哥9 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸10 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp10 小时前
KV Cache 解析
java·算法
liliangcsdn10 小时前
IVOL与偏度因子的对比测量分析
算法
threerocks11 小时前
Jev 入门第一课
算法
西柚研究生12345612 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao173383713 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳14 小时前
2026.9.17
数据结构·算法·leetcode