1. 程式人生 > >LintCode第697題目:判斷是否為平方數之和

LintCode第697題目:判斷是否為平方數之和

使用暴力查詢的時候會超時,暴力查詢演算法:
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;  
    }  
       
    
};