这道题关键在于,我们得灵活思路,能够想到,是对最大的木头长度做二分处理,找出最大公约数。
/**
*@param L: Given n pieces of wood with length L[i]*@param k: An integer
*return: The maximum length of the small pieces.
*/
public int woodCut(int[] L, int k) {
int max = 0;
// 先得到最大长度,
for (int length: L) {
max = Math.max(max, length);
}
// start不可初始值为0!
int start = 1, end = max;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (getCount(L, mid) >= k) {
start = mid;
} else {
end = mid;
}
}
if (getCount(L, end) >= k) {
return end;
} else if (getCount(L, start) >= k) {
return start;
}
return 0;
}
// 得出以这个最大长度,能得到的所有木头切分个数
private int getCount(int[] L, int maxLength) {
int count = 0;
for (int length: L) {
count = count + length / maxLength;
}
return count;
}