#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.
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; }};
- #183 Wood Cut
- wood cut
- wood-cut
- Wood Cut
- Wood Cut
- lintcode:Wood Cut
- Binary Search---Wood Cut
- [LintCode]Wood Cut
- lintcode之Wood-Cut问题
- LintCode Wood Cut java solution
- 二分查找——Wood Cut
- 02分治算法-03wood-cut
- wood
- 183.Wood Cut-木材加工(中等题)
- Slice Wood
- cut
- cut
- cut
- 嵌入元素与图片路径问题
- ReplaceBlank
- C language(未完)
- CodeForces 633C Spy Syndrome 2
- 量化分析师的Python日记[第5天:数据处理的瑞士军刀pandas]
- #183 Wood Cut
- ES java api
- 这两天调试环信的心得
- AOS学习笔记1-------初探
- STL容器简单描述
- 线程源码阅读分析,持续更新中。。。
- 在fragment上的超级复杂之fragmen的平滑切换
- jquery自动补全
- FloatingActionButton 浮动按钮