Tuesday, March 7, 2017

[LintCode] 183 Wood Cut 解题报告

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.

Notice
You couldn't cut wood into float length.

If you couldn't get >= k pieces, return 0.


Example
For L=[232, 124, 456], k=7, return 114.


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

思路
这道题是对答案进行二分法。可能的木头长度是1到最长的那块木头的长度这个范围。那么我们二分start = 1,end = 最长的那块木头。
每次进行判断当前的长度能搞出多少块木头来。如果正好是k块,我们试试再长一点的长度行不行。

Code
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 || k <= 0) {
            return 0;
        }
        
        int start = 1;
        int end = 1;
        for (int wood : L) {
            end = Math.max(wood, end);
        }
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (getPieces(L, mid) >= k) {
                start = mid;
            }
            else {
                end = mid;
            }
        }
        
        if (getPieces(L, end) >= k) {
            return end;
        }
        if (getPieces(L, start) >= k) {
            return start;
        }
        return 0;
    }
    
    public int getPieces(int[] L, int length) {
        int count = 0;
        for (int wood : L) {
            count += wood / length;
        }
        return count;
    }
}