Loading

【leetcode】633. Sum of Square Numbers(two-sum 变形)

  Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

  只要是two_sum 变形 都可以考虑用hash_set来做。

  

class Solution {
public:
    bool judgeSquareSum(int c) {
        //这个和两数之和很想 感觉是两数之和的变形
        //先求一组两平方和之数 如果这两平方和数都存在的话 就返回true
        //用hash_set 存平方和数
        unordered_set<long> res;
        long i=0;
        bool flag=false;
        while(i*i<=c)
        {
            res.insert(i*i);
            i++;
        }
        for(auto a:res)
        {
            if(res.count(c-a))
            {
                flag=true;
                break;
            }
        }
        return flag;
    }
};
  solution2:
class Solution {
public:
    bool judgeSquareSum(int c) {
        //之间判断 用sqrt以及int 数据类型的特性
        for(int i=0;i<=sqrt(c);i++)
        {
            int t=sqrt(c-i*i);
            if(t*t==c-i*i) return true;
        }
        return false;
    }
};

 

  
posted @ 2021-11-19 21:30  aalanwyr  阅读(35)  评论(0编辑  收藏  举报