Leetcode633—平方数之和

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

示例1:

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

这道题的题目理解起来比较容易,就是将一个数分为两个数的平方和,关键就是寻找这两个数是否存在,又是寻找两个数的,拿还是用双指针。

 bool judgeSquareSum(int c) {
        long long first=0;//本来用的int,一直出现超过限制,看了评价改为long long 通过
        long long last=sqrt(c);
        while(first<=last)
        {
            int sum=first*first+last*last;
            if(sum==c)
            {
                return true;
            }
            else if(sum<c)
            {
                first++;
            }
            else{
                last--;
            }
        }
        return false;
    }

看到别人的解题思路一样但是时间更短,看来觉得很奇特,将原始数给减了之后数更小了在比较中消耗的时间更少。

class Solution {
public:
    bool judgeSquareSum(int c) {
        int end=sqrt(c);
        int start=0;
        while(end>=start)
        {
            int res=start*start+(end*end-c);
            if(res==0)
               return true;
            else if(res>0)
               end--;
            else if(res<0)
               start++;
        }
        return false;
    }
};
发布了17 篇原创文章 · 获赞 0 · 访问量 3225

猜你喜欢

转载自blog.csdn.net/qq_31874075/article/details/103995538