Wood Cut

作者: 一枚煎餅 | 来源:发表于2016-09-11 10:13 被阅读0次
Wood Cut.png

===================== 解題思路 =====================

關鍵是找到 binary search 的 right bound ( 最大可能的解 ), 題目告知可以從 vector 裡的最大值著手 所以掃一遍 vector 找到最大值即可用基本 BS 方式解決

===================== C++ code ====================

<pre><code>
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.
 */
bool isValid(vector<int> &L, int mid, int k)
{
    int sum = 0;
    for(int i = 0; i < L.size(); i++)
    {
        sum += L[i] / mid;
    }
    return sum >= k;
}

int woodCut(vector<int> L, int k) {
    // write your code here
    long left = 0, right = 0;
    //get the right bound
    for(int i = 0; i < L.size(); i++)
    {
        if(L[i] > right) right = L[i];
    }
    //binary search
    while(left + 1 < right)
    {
        long mid = left + (right - left) / 2;
        if(isValid(L, mid, k)) left = mid;
        else right = mid;
    }
    if(isValid(L, right, k)) return right;
    else return left;
}

};
<code><pre>

相关文章

  • Wood Cut

    ===================== 解題思路 ===================== 關鍵是找到 bi...

  • 算法题:Wood Cut

    题目: 给定一个数组,数组中的数字代表原木的长度,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数...

  • Wood Cut - solution with binary

    Questions from lintcodeGiven n pieces of wood with length...

  • 2018-06-18 lintCode 183 Wood Cut

    Description Given n pieces of wood with length L[i] (inte...

  • Into the wood

    “Help! A monster!” said Annie. “Yeah, sure,” said Jack. “...

  • wood?

    听音乐的过程就像木头晾干的过程:共振变得越来越好. 人能欣赏一种音乐,说明他和这种音乐有共振。接触的音乐类型越多,...

  • cut and thrust,看这个短语的构造,一定是大架势

    ​cut 对应的习语不少,例如:cut sb some slack,cut to the chase 和 cut ...

  • 2018-02-02

    knock on wood/touch wood means:祈求好运 I'm expecting a raise...

  • 木林森

    wood 木woods 林forest 森林jungle 热带森林 . 【wood】 木This table is...

  • 72. A walk through the woods. 林中

    1. 单词部分 surround 包围 wood 树林wood n. 木头the woods 树林 beauty ...

网友评论

      本文标题:Wood Cut

      本文链接:https://www.haomeiwen.com/subject/geduettx.html