使用暴力查找的时候会超时,暴力查找算法:
public class Solution { /* * @param : the given number * @return: whether whether there're two integers */ public boolean checkSumOfSquareNumbers(int num) { // write your code here for(int i=0;i*i<=num;i++){ for(int j =0;(j*j+i*i)<=num;j++){ if(j*j+i*i==num){ return true; } } } return false; } }; 此种算法可以通过:
public class Solution { /* * @param : the given number * @return: whether whether there're two integers */ public boolean checkSumOfSquareNumbers(int num) { // write your code here if(num<0){ return false; } Map<Integer,Integer> map = new HashMap<>(); int tmp = (int)Math.sqrt(num); if(tmp * tmp == num){ return true; } for(int i = 0; i <= tmp; i++){ map.put(i*i,i*i); } for(int i = tmp; i >= tmp/2; i--){ if(map.get(i*i)!=null){ if(map.containsKey(num - map.get(i*i))){ return true; } } } return false; } };