有一些原木,現在想把這些木頭切割成一些長度相同的小段木頭,需要得到的小段的數目至少爲 k
。當然,我們希望得到的小段越長越好,你需要計算能夠得到的小段木頭的最大長度。
樣例
有3根木頭[232, 124, 456]
, k=7
,
最大長度爲114
.
注意
木頭長度的單位是釐米。原木的長度都是正整數,我們要求切割得到的小段木頭的長度也要求是整數。無法切出要求至少 k 段的,則返回 0
即可。
挑戰
O(n log Len), Len爲 n 段原木中最大的長度
本質上仍舊採用二分法的思想,但是在這裏,查找到最大的可滿足的條件,即把1當做搜索的底,吧最大長度len當做搜索的最大值,而對於對於原版判斷條件,改成是否滿足切割
class Solution {
public:
/**
*@param L: Given n pieces of wood with length L[i]
*@param k: An integer
*return: The maximum length of the small pieces.
*/
int woodCut(vector<int> L, int k) {
// write your code here
if(L.size()==0)
return 0;
long long sum = 0;
for(auto x:L)
sum += x;
if(sum < k)
return 0;
long long len = *max_element(L.begin(),L.end());
long long l=1,r=len;
while(l<r)
{
long long mid = (l+r+1)/2;
if(ok(L,k,mid))
l = mid;
else
r = mid-1;
}
return l;
}
private:
bool ok(const vector<int>& L, const int k,const long long len)
{
long long cnt = 0;
for(auto x:L)
cnt += x/len;
return cnt >= k;
}
};