#183 Wood Cut

来源:互联网 发布:hello软件 编辑:程序博客网 时间:2024/04/28 04:38

题目描述:

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.

Example

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

题目思路:

这题的时间复杂度要求为O(nlogn),从中可以看出可以用binary search来解。首先,判定两个特殊case:

1. L 为空的情况下,return 0

2. 当假定最大wood 长度为1的情况下,仍然只能砍到 < k根木头,则也return0

排除了上述case,就可以进行常规的binary search了:

最终答案应该在1~L中最大wood length之间。每次得到mid之后,计算可以砍到多少根木头;如果 >= k,则可以放大mid;反之则减小mid。这里while的条件为shortest + 1 < longest,这是考虑到shortest 和longest都是int,如果不加一则可能得到死循环。

Mycode(AC = 96ms):

class Solution {public:    /**      *@param L: Given n pieces of wood with length L[i]     *@param k: An integer     *return: The maximum length of the small pieces.     */    int woodCut(vector<int> L, int k) {        // write your code here        // consider L is empty case        if (L.size() == 0) {            return 0;        }                // computePieces() can't take length == 0 case        // hence, consider if length == 1 can't chop out        // k woods, then return 0        if (computePieces(L, 1) < k) return 0;                // the possible answer includes 1~max_len, compute        // max_len first        int max_len = 1;        for (int i = 0; i < L.size(); i++) {            max_len = max(max_len, L[i]);        }                // binary search between 1 ~ max_len        long long shortest = 1, longest = max_len;        while (shortest + 1 < longest) {            long long mid = (longest - shortest)/2 + shortest;            long long pieces = computePieces(L, mid);                        if (pieces >= k) {                shortest = mid;            }            else {                longest = mid;            }        }        return (int)shortest;    }        // compute how many wood pieces can be cut given L and     // required wood length    long long computePieces(vector<int>& L, int len) {        long long pieces = 0;        for (int i = 0; i < L.size(); i++) {            pieces += L[i] / len;        }        return pieces;    }};

0 0
原创粉丝点击