标签:@param while des amp 14. pie nlog for oat
Topic: Binary Search
Given n pieces of wood with length L[i] (integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.
Example
For L=[232, 124, 456], k=7, return 114.
Challenge
O(n log Len), where Len is the longest length of the wood.
Notice
You couldn‘t cut wood into float length.
If you couldn‘t get >= k pieces, return 0.
class Solution:
"""
@param L: Given n pieces of wood with length L[i]
@param k: An integer
@return: The maximum length of the small pieces
"""
def woodCut(self, L, k):
# write your code here
# write your code here
if L == []:
return 0
L.sort()
max = L[-1]
l = 1
r = L[-1]
while(l<=r):
count = 0
m = (l + r) // 2
print(l,r,m)
for i in L:
count += i//m
if count>=k:
l = m+1
else:
r = m-1
#1.边界问题,最后结果可能是从右向左逼近,此时m为第一个不满足条件的情况,反之,从左往右逼近,则m为满足条件的情况
print(m)
count = 0
for i in L:
count += i//m
print(count)
if count >= k:
return m
else:
return m-1
标签:@param while des amp 14. pie nlog for oat
原文地址:https://www.cnblogs.com/siriusli/p/10358600.html