您的位置:首页 > 其它

LeetCode 633. Sum of Square Numbers

2018-02-15 07:48 435 查看

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

 

题目标签:Math

  大家今天情人节快乐哈!祝贺单身狗们节日快乐! (美国时间还在 2/14)

  我给大家唱首歌:single dog, single dog, single all the way... 刷题吧!

 

  题目给了我们一个 c,让我们找到 a * a + b * b = c。

  这里可以利用 two pointers, left 和 right,left = 0, right =  Math.sqrt(c)。

  当 left 小于等于 right的情况下:sum = left * left + right * right

    如果 sum 大于 c 的话,说明 需要更小的,right--;

    如果 sum 小于 c 的话,说明 需要更大的,left++;

    如果 sum 等于 c,返回 true。

 

 

Java Solution:

Runtime beats 85.71% 

完成日期:02/14/2018

关键词:Math

关键点:利用 two pointers 从 0 到 Math.sqrt(c) 的范围

class Solution
{
public boolean judgeSquareSum(int c)
{
int left = 0;
int right = (int)Math.sqrt(c);

while(left <= right)
{
int sum = left * left + right * right;

if(sum == c)
return true;
else if(sum < c)
left++;
else
right--;

}

return false;
}
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: