Python世界:力扣题633,平方数之和,中等

Python世界:力扣题633,平方数之和,中等

任务背景


问题来自力扣题目633. Sum of Square Numbers,大意如下:

Given a non-negative integer c, decide whether there're two integers a and b such that a^2 + b^2 = c.

翻译下,需求是:对给定数字c,确定是否有两个整数满足a^2+b^2=c

思路分析


二分法思路

  • 默认a,b均为非负,且b不小于a
  • 在0-sqrt©之间遍历a,直到a=b相遇或a>b跳出循环
  • cs = sqrt©
  • 此移动方式不通
    • 若b=sqrt(c-a^2) 圆整后,重加回满足目标,且b不小于a中断
    • 若b<a,a收缩为下界
    • 若b>a,a收缩为上界
  • 换为low/high双指针左右移动
    • 将0-cs之间的数平方和组合罗列为一种有序组合
    • 初始位:t = low2+high2,是在有序组合的中间
    • 若t > c,则缩小high
    • 若t < c,则增大low
    • 与纯二分区别在于,不仅单一mid在移动

代码实现


python 复制代码
import math

class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        res = False
        cs = int(math.sqrt(c)) + 1
        low = 0
        high = cs
        while (low <= high): # two pointer
            t = low**2 + high**2
            if (t < c):
                low += 1
            elif (t > c):
                high -= 1
            else:
                return True
        return res

测试套件


单例测试demo:

python 复制代码
# one case test
c = 5 # 1+4
c = 4 # 0+4
c = 3 # false
c = 13 # 4+9
c = 12 # false
c = 169 # 12^2+5^2

sol = Solution()
res = sol.judgeSquareSum(c)
print(res)

测试套demo:

python 复制代码
# 导入单元测试
import unittest


def test_base(self, c, ret):
    sol = Solution()
    res = sol.judgeSquareSum(c)
    self.assertEqual(res, ret)    


# 编写测试套
class TestSol(unittest.TestCase):
    # 不在
    def test_special1(self):
        c = 3
        ret = False
        test_base(self, c, ret)

    # 下边界
    def test_special2(self):
        c = 0
        ret = True
        test_base(self, c, ret)

    # 上边界
    def test_special3(self):
        c = 2**31 - 1
        ret = False
        test_base(self, c, ret)

    def test_common1(self):
        c = 5
        ret = True
        test_base(self, c, ret)

    def test_common2(self):
        c = 13
        ret = True
        test_base(self, c, ret)

    def test_common3(self):
        c = 169
        ret = True
        test_base(self, c, ret)


# 含测试套版本主调
if __name__ == '__main__':
    print('start!')
    unittest.main() # 启动单元测试
    print('done!')

本文小结


本题思路很简单,只为重温下二分写法,发现值大的下移上界,发现值小的上移下界,直到上下界重合。要特别注意的是无target时,mid的偏移问题。

相关推荐
Swift社区2 分钟前
LeetCode 401 二进制手表 - Swift 题解
算法·leetcode·swift
CAE虚拟与现实3 分钟前
Python在Windows 平台上引入了一种新的安装与运行时管理机制
开发语言·python
财经资讯数据_灵砚智能6 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年4月4日
大数据·人工智能·python·信息可视化·自然语言处理·ai编程
数据知道8 分钟前
Claude Code 进行“从头重写”的项目 Claw Code全面介绍(claw-code)
python·ai·claude code
ZHENGZJM15 分钟前
用大语言模型(LLM)自动化扩充 OJ 系统测试数据:Python 脚本实战
python·语言模型·自动化
Hello eveybody17 分钟前
图论简述+图论考试要点(Python)
开发语言·python·图论
memcpy023 分钟前
LeetCode 3634. 使数组平衡的最少移除数目【排序+滑动窗口】1453
算法·leetcode·职场和发展
被放养的研究生24 分钟前
算法比赛用到的函数或模块(Python)
windows·python·算法
Hello eveybody25 分钟前
二叉树简述+考试要点(Python)
开发语言·python
第二只羽毛28 分钟前
C++高性能内存池6(面试题)
大数据·开发语言·c++