中=低+(高-低)// 2相比(低+高)// 2有什么好处?

时间:2019-04-10 11:57:09

标签: python

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

  

给出一个数组,其中元素按升序排序,将其转换为高度平衡的BST。

     

对于此问题,将高度平衡的二叉树定义为二叉树,其中每个节点的两个子树的深度相差不超过1。

     

示例:

     
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有什么好处?

2 个答案:

答案 0 :(得分:2)

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

…但是在Python中,没有整数溢出,因此您可以执行(low + high) // 2

答案 1 :(得分:1)

许多语言,例如C ++,JAVA。整数具有固定值范围,例如:

int32:-2147483648〜2147483647
int64:-9223372036854775808〜9223372036854775807

有时会在有效范围内上下波动,但是0 01-01-2001 1.002500 1.601591 ... NaN NaN NaN 1 02-01-2001 0.978400 1.608285 ... NaN NaN NaN 2 03-01-2001 0.962800 1.606327 ... NaN NaN NaN 3 04-01-2001 0.956900 1.591041 ... NaN NaN NaN 4 05-01-2001 0.911300 1.567882 ... NaN NaN NaN 5 Average rate 0.906352 1.544086 ... NaN NaN NaN 6 06-01-2001 0.927400 1.571944 ... NaN NaN NaN 7 07-01-2001 0.958600 1.558775 ... NaN NaN NaN 8 08-01-2001 0.926600 1.546576 ... NaN NaN NaN 9 09-01-2001 0.889100 1.549333 ... NaN NaN NaN 10 10-01-2001 0.882500 1.525312 ... NaN NaN NaN 11 11-01-2001 0.853910 1.512577 ... NaN NaN NaN 12 Average rate 0.906352 1.544086 ... NaN NaN NaN 可能会溢出。

因此使用low + high

这样的差异更为安全

但是对于python来说不​​是必需的,因为它在Java中的作用类似于mid = low + (high -low)//2