183. Wood Cut (题目链接)
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
Example 1
Input:
L = [232, 124, 456]
k = 7
Output: 114
Explanation: We can cut it into 7 pieces if any piece is 114cm long, however we can't cut it into 7 pieces if any piece is 115cm long.
Example 2
Input:
L = [1, 2, 3]
k = 7
Output: 0
Explanation: It is obvious we can't make it.
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
.
思路:
一开始直接暴力搜索,结果超时。看题解说是可以二分,那么怎么二分?
找到最长的木棍,对该木棍进行二分,如果分得的木棍个数符合要求,l = m + 1,否则r = m - 1
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 he
if not L:
return 0
length = L[0]
for wood in L[1:]:
length = max(wood, length)
l, r = 1, length
rlt = 0
while l <= r:
m = (l + r) // 2
cnt = 0
for wood in L:
temp = wood // m
if temp > 0:
cnt += temp
if cnt >= k:
l = m + 1
rlt = m
else:
r = m - 1
return rlt