[LintCode] 183. Wood Cut
作者:互联网
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.
The unit of length is centimeter.The length of the woods are all positive integers,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 114 long, however we can't cut it into 7 pieces if any piece is 115 long.
And for the 124 logs, the excess can be discarded and not used in its entirety.
Example 2
Input:
L = [1, 2, 3]
k = 7
Output: 0
Explanation: It is obvious we can't make it.
Challenge
O(n log Len), where Len is the longest length of the wood.
木材加工。
有一些原木,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数目至少为 k
。给定L和k,你需要计算能够得到的小段木头的最大长度。
这道题的思路是二分,而且是在答案上二分。对于所有的木头而言,切割的长度的下界是1,上界是最长的那个木材的长度。在这个范围内进行二分,用每次二分得到的潜在的mid长度再去计算到底能切割成几个小段。
时间O(nlogn)
空间O(1)
Java实现
1 public class Solution { 2 /** 3 * @param l: Given n pieces of wood with length L[i] 4 * @param k: An integer 5 * @return: The maximum length of the small pieces 6 */ 7 public int woodCut(int[] logs, int k) { 8 // write your code here 9 int len = logs.length; 10 long sum = 0; 11 int max = 0; 12 for (int log : logs) { 13 max = Math.max(max, log); 14 sum += log; 15 } 16 // corner case 17 if (sum < k) { 18 return 0; 19 } 20 21 // normal case 22 int left = 1; 23 int right = max; 24 while (left + 1 < right) { 25 int mid = left + (right - left) / 2; 26 if (isValid(logs, k, mid)) { 27 left = mid; 28 } else { 29 right = mid; 30 } 31 } 32 if (isValid(logs, k, right)) { 33 return right; 34 } 35 return left; 36 } 37 38 private boolean isValid(int[] logs, int k, int mid) { 39 int count = 0; 40 for (int log : logs) { 41 count += log / mid; 42 } 43 if (count >= k) { 44 return true; 45 } 46 return false; 47 } 48 }
标签:Cut,return,logs,int,mid,pieces,183,length,Wood 来源: https://www.cnblogs.com/cnoodle/p/16329100.html