python - `mid = low + (high -low)//2` 比 `(low + high)//2` 有什么好处?

标签 python

我正在研究树问题 Convert Sorted Array to Binary Search Tree - LeetCode

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

直观的 D&Q 解决方案是

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        """
        Runtime: 64 ms, faster than 84.45%
        Memory Usage: 15.5 MB, less than 5.70% 
        """
        if len(nums) == 0: return None
        #if len(nums) == 1: return TreeNode(nums[0])
        mid = len(nums) // 2
        root = TreeNode(nums[mid])
        if len(nums) == 1: return root 
        if len(nums) > 1: 
            root.left = self.sortedArrayToBST(nums[:mid])
            root.right = self.sortedArrayToBST(nums[mid+1:])
        return root        

mid 设置为 len(nums)//2(low + high)//2

当阅读其他提交的内容时,我发现

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        return self.buildBST(nums, 0, len(nums))

    def buildBST(self, nums, left, right):
        if right <= left:
            return None
        if right == left + 1:
            return TreeNode(nums[left])

        mid = left + (right - left) // 2
        root = TreeNode(nums[mid])
        root.left = self.buildBST(nums, left, mid)
        root.right = self.buildBST(nums, mid + 1, right)

        return root

mid 设置为 mid = low + (high -low)//2

mid = low + (high -low)//2 相对于 (low + high)//2 有何优势?

最佳答案

这是一种避免整数溢出的模式;该代码可能是从具有固定大小整数的语言移植的。当索引变得与用于包含它们的类型一样大时,中间 low + high 值的溢出就会成为问题,导致未定义的行为、不正确的结果和漏洞。 (当您是 searching something that’s not an array 时,这种情况甚至会发生在像 size_t 这样的大整数类型上。)

…但是在Python中,不存在整数溢出,所以你是对的,你可以做(low + high)//2

关于python - `mid = low + (high -low)//2` 比 `(low + high)//2` 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611990/

相关文章:

Python加速大型嵌套数组处理

python - 如何在 Python 中将并集/交集方法作为参数传递?

python - 使用 RapydScript 通过 Python 和 DOM 进行简单的图像旋转

python - 我的 Flask 应用程序中出现 RuntimeError : Working outside of application context.

python - 如何计算 Pandas 每周中每天最大值的最常见时间

python - 使用python检测音频文件完整性

Python 换行符\n 在 jupyter 笔记本中不起作用

python - 字符串值错误错误 - Python + mariaDB

Python 值错误 : unconverted data remains:

python - 如何使用 python 通过公共(public) IP 连接到 MySQL?