【LeetCode】Sum of Square Numbers 解题报告

来源:互联网 发布:数据挖掘的特点 编辑:程序博客网 时间:2024/06/13 22:08

【LeetCode】Sum of Square Numbers 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/sum-of-square-numbers/discuss/

题目描述:

Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.

Examle:

Example 1:Input: 5Output: TrueExplanation: 1 * 1 + 2 * 2 = 5Example 2:Input: 3Output: False

Ways

方法一:双指针,比较好理解

class Solution(object):    def judgeSquareSum(self, c):        """        :type c: int        :rtype: bool        """        left = 0        right = int(c ** 0.5)        while left <= right:            cur = left ** 2 + right ** 2            if cur < c:                left += 1            elif cur > c:                right -= 1            else:                return True        return False

方法二:使用列表生成式。xrange是个生成式,range返回的是列表。判断去除一个平方数之后剩余的数是不是平方数。

class Solution(object):    def judgeSquareSum(self, c):        """        :type c: int        :rtype: bool        """        def is_square(N):            return int(N ** 0.5) ** 2 == N        return any(is_square(c - a ** 2) for a in xrange(int(c ** 0.5) + 1))

Date

2017 年 8 月 24 日

原创粉丝点击