LeetCode #633 平方数之和 双指针

LeetCode #633 平方数之和

题目描述

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

示例1:

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

示例2:

输入: 3
输出: False

思路分析

思路跟 LeetCode #167 两数之和II - 输入有序数组 双指针 一样,只是从和变成了积。本题的关键在于右指针的初始化,因右指针最大就为 target 的开根号,此时 0 2 + t a r g e t = t a r g e t 0^2 + target = target ,所以可以将右指针取为 i n t ( s q r t ( t a r g e t ) ) int(sqrt(target)) ,左指针初始化为 0,实现剪枝。

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        if c < 0: return False
        a = 0; b = int(math.sqrt(c))

        while(a <= b):
            powSum = a**2 + b**2
            if powSum == c:
                return True
            elif powSum < c:
                a += 1
            else:
                b -= 1
        
        return False
发布了67 篇原创文章 · 获赞 2 · 访问量 1358

猜你喜欢

转载自blog.csdn.net/weixin_42511320/article/details/105177022
今日推荐