问题描述:给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c
。
示例1:
输入:c = 5 输出:true 解释:1 * 1 + 2 * 2 = 5
示例2:
输入:c = 3
输出:false
示例3:
输入:c = 4
输出:true
示例4:
输入:c = 2
输出:true
示例5:
输入:c = 1
输出:true
解题思路:
这题我的思路是采取的是双指针。依题可知判断是否存在两个整数a和b使得,我们可以得到a与b的范围一定在[0,]之间,故使用指针i指向区间最左端,指针j指向指针最右端。初始标志flag=0表示未找到符合要求的两个数。
算法步骤:判断是否满足,若是,则向左移动尾指针j,若i^2+j^2<c,则向右移动头指针i,如果i^2+j^2=c,标志flag更新为1,并退出遍历,已找到这两个整数。重复上述步骤,直至遍历结束,判断标志flag是否为1,若是则返回true,否则返回false。此时算法复杂度为O()
import java.util.Scanner;
import java.lang.Math;
//给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
public class Leetcode_633 {
public boolean judgeSquareSum(int c) {
int s_c = (int)Math.sqrt(c);
int i=0,j=s_c;
int flag = 0;
if (c==1 || c==0)
return true;
while(i<=j){
if (Math.pow(i,2)+Math.pow(j,2) < c)
i++;
else if (Math.pow(i,2)+Math.pow(j,2) > c)
j--;
else {
flag=1;
break;
}
}
if (flag==1)
return true;
return false;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
Leetcode_633 l = new Leetcode_633();
long start = System.currentTimeMillis();
boolean flag = l.judgeSquareSum(c);
long end = System.currentTimeMillis();
System.out.print(flag);
System.out.print(end-start);
}
}