今天刷题的时候遇到一个题目,题目不难,但是一时间没想出来怎么算,现在总结一下题目的想法。
题目描述:
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.
Notice
You couldn't cut wood into float length.
If you couldn't get >= k pieces, return 0.
Example
For L=[232, 124, 456], k=7, return 114.
题目分析:
题目的意思就是给定一个数组L,数字k,将数组中的木头长度分成至少k段长度相同的木头,并且求分成小木头后其最大长度。
可以写出两个函数,第一个函数为countPieces(vector<int> L, int len),输入数组L和长度len,返回最多可分为多少段。第二个函数为woodCut(vector<int> L, int k),输入数组长度L和最少分成的k段木头数,输出最终结果。在第二个函数中,可以采用二分法,先找出数组L中的木头最长的长度maxLen,然后设置shortest = 1,longest = maxLen,进行二分调用,每次需要调用countPieces测试分段总数是否大于等于k。此处需要注意,二分循环的条件是shortest+1<longest。
代码如下:
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) {
if(L.size()==0 || countPieces(L, 1)<k)
return 0;
int maxLen=1;
for(int i=0;i<L.size();i++)
maxLen=max(maxLen, L[i]);
int shortest = 1, longest = maxLen;
while(shortest+1<longest){
int mid = shortest + (longest-shortest)/2;
if(countPieces(L, mid)>=k)
shortest = mid;
else
longest = mid;
}
if(countPieces(L, longest)>=k)
return longest;
return shortest;
}
private:
long long countPieces(vector<int> &L, int len){
long long pieces = 0;
for(int i=0;i<L.size();i++)
pieces += L[i]/len;
return pieces;
}
};
总结:
题目不难,需要多思考,多动动脑筋。