首页 > 其他 > 详细

Wood Cut

时间:2019-12-21 21:23:49      阅读:107      评论:0      收藏:0      [点我收藏+]

Description

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

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.

Challenge

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;
    }
}

  

 

Wood Cut

原文:https://www.cnblogs.com/FLAGyuri/p/12078123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!