判断是否为平方数之和-LintCode

来源:互联网 发布:网络游戏破解软件大全 编辑:程序博客网 时间:2024/06/06 19:02

给一个整数 c, 你需要判断是否存在两个整数 a 和 b 使得 a^2 + b^2 = c.

样例:
给出 n = 5
返回 true // 1 * 1 + 2 * 2 = 5
给出 n = -5
返回 false

思路:
构建set包含0*0,1*1,…,cc
利用指针it,遍历set,查找是否有元素等于c-*it,
若存在,返回true

#ifndef C697_H#define C697_H#include<iostream>#include<set>#include<math.h>using namespace std;class Solution {public:    /*    * @param : the given number    * @return: whether whether there're two integers    */    bool checkSumOfSquareNumbers(int num) {        // write your code here        if (num < 0)            return false;        int n = (int)sqrt(num);        set<int> set;        for (int i = 0; i <= n; ++i)            set.insert(i*i);        for (auto it = set.begin(); it != set.end(); ++it)        {            if (set.find(num - *it) != set.end())            {                return true;            }        }        return false;    }};#endif
原创粉丝点击