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

Wood Cut

时间:2017-05-28 09:51:59      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:print   max   也有   class   end   else   blog   i++   tpi   

Note:

审题: 注意也有一种情况是: 一共有N个元素,要k个,但有不需要从每一个块去取, 只需要从其中的一些取。所以这里end开始应该取最大的element。而且有可能完全取不到,所以start应该从0开始取。剩下的和copy book那道题想法一致。

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) {
        // write your code here
        if (L == null || L.length == 0) {
            return 0;
        }
        
        int start = 0;
        int end = L[0]; 
        for (int i = 0; i < L.length; i++) {
            if (end < L[i]) {
                end = L[i];
            }
        }
        
        //System.out.println(end + " " + start);
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int tmp = countPiece(L, mid);
            //System.out.println(tmp + " " + start + " " + end + " " + mid);
            if (countPiece(L, mid) >= k) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        //System.out.println(start + " " + end);
        
        if (countPiece(L, end) >= k) {
            return end;
        }
        return start;
    }
    
    private int countPiece(int[] L, int maxlen) {
        int count = 0;
        for (int i = 0; i < L.length; i++) {
            count += L[i] / maxlen;
        }
        return count;
    }
}

 

Wood Cut

标签:print   max   也有   class   end   else   blog   i++   tpi   

原文地址:http://www.cnblogs.com/codingEskimo/p/6914936.html

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