您的位置:首页 > 其它

LintCode Wood Cut

2015-09-13 12:23 211 查看

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.

Have you met this question in a real interview? Yes

Example

For L=[232, 124, 456], k=7, return 114.

Note

You couldn't cut wood into float length.

Challenge

O(n log Len), where Len is the longest length of the wood.


这个好像在挑战编程里看到过类似的,用二分搜索,用upper_bound的思想,注意除零的情况。

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
long lo = 0;
long hi = 0;
for (int e : L) {
if (hi < e) {
hi = e;
}
}

hi++;
while (lo < hi) {
long mid = (lo + hi) / 2;
if (mid == 0) {
return 0;
}
long tryK = pieces(L, mid);
if (tryK >= k) {
lo = mid + 1;
} else {
hi = mid;
}
}

return lo - 1;
}

long pieces(vector<int>& L, long len) {
int count = 0;
for (int e : L) {
count += e / len;
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: