Skip to content

Commit

Permalink
递归二分
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed Mar 19, 2019
1 parent ceb2309 commit 2f5a1fa
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions 1014. Capacity To Ship Packages Within D Days.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
"""
解法:二分搜索
target = D,也就是说,当天数恰好为D时,返回重量。
"""

def count_days(weight):
"""
当重量为weight时,返回需要的天数
"""
if weight < mi:
return D + 1
count = 1
tem = weight
for x in weights:
if tem >= x:
tem -= x
else:
count += 1
tem = weight - x
return count

def bin_search(low, high):
if low > high:
return low
mid = (low + high) // 2
days = count_days(mid)
print(mid, days)
if days <= D:
return bin_search(low, mid - 1)
else:
return bin_search(mid + 1, high)

if len(weights) < D:
return max(weights)
mi = max(weights)
ma = sum(weights)
return bin_search(mi, ma)

0 comments on commit 2f5a1fa

Please sign in to comment.