leetcode 633. Sum of Square Numbers 二分查找+勾股定理
2017-12-19 20:48
555 查看
Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
本题很简单,就是寻找勾股数,我最初的想法是直接暴力求解但是发现太笨了,后来在网上看到了一个二分查找的做法,十分棒,值得学习
代码如下:
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
本题很简单,就是寻找勾股数,我最初的想法是直接暴力求解但是发现太笨了,后来在网上看到了一个二分查找的做法,十分棒,值得学习
代码如下:
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <numeric> #include <cmath> #include <regex> using namespace std; class Solution { public: bool judgeSquareSum(int c) { if (c < 0) return false; int left = 0, right = (int)sqrt(c); while (left <= right) { int res = left*left + right*right; if (res < c) left++; else if (res > c) right--; else return true; } return false; } };
相关文章推荐
- leetcode 153. Find Minimum in Rotated Sorted Array-二分查找|递归|非递归
- Leetcode 633. Sum of Square Numbers(Easy)
- leetcode 633. Sum of Square Numbers
- [C++]LeetCode: 132 Find Minimum in Rotated Sorted Array II (二分查找)
- [leetcode]633. Sum of Square Numbers
- leetcode First Bad Version(二分查找)
- leetcode 397. Integer Replacement 二分查找 + 深度优先遍历DFS
- leetcode第十五周解题总结--二分查找(二)
- leetcode 154. Find Minimum in Rotated Sorted Array II 旋转数组(重复)+二分查找
- [leetcode-二分查找]--34. Search for a Range
- leetcode二分查找问题整理
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- LeetCode-Search for a Range-搜索范围-二分查找
- Leetcode 35 Search Insert Position 二分查找(二分下标)
- leetcode_81——Search in Rotated Sorted Array II(二分查找)
- LeetCode之Insert Interval--二分查找
- LeetCode 633. Sum of Square Numbers
- [LeetCode 33]Search in Rotated Sorted Array (二分查找)
- ※ Leetcode - Binary Search - 153. Find Minimum in Rotated Sorted Array(二分查找)
- 【leetcode】查找插入位置(二分)