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.
You couldn‘t cut wood into float length.
If you couldn‘t get >= k pieces, return 0
.
Example 1
Input:
L = [232, 124, 456]
k = 7
Output: 114
Explanation: We can cut it into 7 pieces if any piece is 114cm long, however we can‘t cut it into 7 pieces if any piece is 115cm long.
Example 2
Input:
L = [1, 2, 3]
k = 7
Output: 0
Explanation: It is obvious we can‘t make it.
O(n log Len), where Len is the longest length of the wood.
思路:采用二分答案的方法,二分最长数额,如果可以完成,就增大,如果不能,就减小。
public 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. */ public int woodCut(int[] L, int k) { int l = 1, res = 0; int r = 0; for (int item : L) { r = Math.max(r, item); } while (l <= r) { int mid = l + (r - l) / 2; // (l + r) / 2 may overflow if (count(L, mid) >= k) { res = mid; l = mid + 1; } else { r = mid - 1; } } return res; } private int count(int[] L, int len) { int sum = 0; for (int item : L) { sum += item / len; } return sum; } }
原文:https://www.cnblogs.com/FLAGyuri/p/12078123.html