# 木材加工（LintCode）

#### 木材加工

O(n log Len), Len为 n 段原木中最大的长度

 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[] L, int k) {
8         if (L.length == 0) {
9             return 0;
10         }
11         long sum = L[0];
12         long max = L[0];
13
14         for (int i=1;i<L.length;i++) {
15             sum += L[i];
16             max = Math.max(L[i],max);
17         }
18         if (sum < k) {
19             return 0;
20         }
21
22         long i = 1;
23         long j = max;
24
25         while(i <= j) {
26             long mid = (i + j) / 2;
27             if (judge(L,k,mid)) {
28                 i = mid + 1;
29             }else {
30                 j = mid - 1;
31             }
32         }
33
34         return (int)j;
35     }
36
37     public boolean judge(int[] L,int k,long l){
38         int num = 0;
39         for (int x : L) {
40             num += x/l;
41         }
42         if (num >= k) {
43             return true;
44         }
45         return false;
46     }
47 }

posted @ 2015-12-12 17:23  -.-|  阅读(734)  评论(0编辑  收藏