165.Sum of Square Numbers
题目:
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.
给定非负整数c,您的任务是确定是否存在两个整数a和b,使得a2 + b2 = c。
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False
解答:
方法一:
1 class Solution { 2 public boolean judgeSquareSum(int c) { 3 for(int i=0;i<=Math.sqrt(c);i++){ 4 int b=c-i*i; double t=Math.sqrt(b); 5 if(Math.floor(t)==t) return true;//判断b是不是完全平方数 6 } 7 return false; 8 } 9 }
方法二:利用集合
1 class Solution { 2 public boolean judgeSquareSum(int c) { 3 Set<Integer> set=new HashSet<>(); 4 for(int i=0;i<=Math.sqrt(c);i++){ 5 set.add(i*i); 6 if(set.contains(c-i*i)) 7 return true; 8 } 9 return false; 10 } 11 }
方法三:利用大小两个指针
1 class Solution { 2 public boolean judgeSquareSum(int c) { 3 int a=0,b=(int)Math.sqrt(c); 4 while(a<=b){ 5 if(a*a+b*b==c) return true; 6 else if(a*a+b*b<c) a++; 7 else b--; 8 } 9 return false; 10 } 11 }
详解: