您的位置:首页 > 其它

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

2017-11-22 16:07 211 查看
给一个整数 c, 你需要判断是否存在两个整数 a 和 b 使得 a^2 + b^2 = c.

样例:

给出 n = 5

返回 true // 1 * 1 + 2 * 2 = 5

给出 n = -5

返回 false

思路:

构建set包含0*0,1*1,…,c√∗c√

利用指针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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: