Algorithm -Binary for ShipwithDays LC

Algorithm -Binary for ShipwithDays LC

1 Analysis

Binary的典型应用,将重量作为左右边界, 用middle value来计算天数, 用天数来作为二分法的分节点,对综合知识以及实际问题处理想法的考察。

2 Coding

class Solution:
    def shipWithinDays1(self, weights, D):
        left, right = max(weights), sum(weights) # 船一次运送的最小和最大范围
        # 二分法
        while left < right:
            mid = (left + right) // 2
            times, temp_weights = 1, 0
            for num in weights:
                if temp_weights + num > mid:
                    times += 1
                    temp_weights = 0
                temp_weights += num
                if times > D:
                    break

            if times <= D:  # 总次数小, 说明装货太多, each weight太高
                right = mid
            else:
                left = mid + 1
        return left
'''

猜你喜欢

转载自blog.csdn.net/minovophy/article/details/121529104