LintCode第697题目:判断是否为平方数之和

来源:互联网 发布:上饶师范学院网络教务 编辑:程序博客网 时间:2024/06/06 02:53
使用暴力查找的时候会超时,暴力查找算法:
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;      }             };