[Lintcode]183. Wood Cut
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]183. Wood Cut相关的知识,希望对你有一定的参考价值。
183. Wood Cut
- 本题难度: Hard
Topic: Binary Search
Description
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
思路
- 切割的大小肯定小于最长木料长度,而从最长木料选择截取特定长的的时间复杂度是log(L)
- 共有n块木料,每个特定的长度要试n次
- 时间复杂度: nlog(L) L为最长木料长度
- 出错
想得挺顺利的,就是一个边界问题没考虑好,最后结果可能是从右向左逼近,此时m为第一个不满足条件的情况,反之,从左往右逼近,则m为满足条件的情况
也有低级错误
以上是关于[Lintcode]183. Wood Cut的主要内容,如果未能解决你的问题,请参考以下文章
linux cut: invalid byte, character or field list Try 'cut --help' for more information.(示例代