Leetcode633题平方数之和

题目

给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a*a + b*b = c。

示例

输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5

输入: 3
输出: False

题解

本题利用双指针法进行求解,与两数之和一样思路,其中注意先限定好右指针的范围降低时间复杂度。

class Solution {
    public boolean judgeSquareSum(int c) {
        //本题利用双指针法进行求解,与两数之和一样思路,先限定好右指针的范围降低时间复杂度
        int left = 0;
        int right = (int)Math.sqrt(c);    //限定好右指针范围
        while(left <= right){
            int a = left * left + right * right;
            if(a == c){
                return true;
            }
            else if(a > c){
                right--;
            }
            else{
                left++;
            }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/jianglinliu/p/11872215.html