码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode: Wood Cut

时间:2016-01-06 06:49:55      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:

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.

Have you met this question in a real interview? Yes
Example
For L=[232, 124, 456], k=7, return 114.

Note
You couldn‘t cut wood into float length.

Challenge
O(n log Len), where Len is the longest length of the wood.

注意是在[1,max(L)]里面找

 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         // write your code here
 9         if (L==null || L.length==0 || k<=0) return 0;
10         Arrays.sort(L);
11         int l=1, r=L[L.length-1];
12         while (l <= r) {
13             int m = l+(r-l)/2;
14             if (calc(L, m)>=k) l=m+1;
15             else r=m-1;
16         }
17         return r;
18     }
19     
20     public int calc(int[] L, int len) {
21         int res = 0;
22         for (int i=0; i<L.length; i++) {
23             res += L[i]/len;
24         }
25         return res;
26     }
27 }

 

Lintcode: Wood Cut

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5104287.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!