码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode633题平方数之和

时间:2019-11-16 17:24:43      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:判断   math   strong   square   color   两数之和   solution   span   题解   

题目

给定一个非负整数 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;
    }
}

 

 

Leetcode633题平方数之和

标签:判断   math   strong   square   color   两数之和   solution   span   题解   

原文地址:https://www.cnblogs.com/jianglinliu/p/11872215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!