zoukankan      html  css  js  c++  java
  • LintCode Wood Cut

    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.
    Have you met this question in a real interview? Yes
    Example
    For L=[232, 124, 456], k=7, return 114.
    Note
    You couldn't cut wood into float length.
    Challenge
    O(n log Len), where Len is the longest length of the wood.

    这个好像在挑战编程里看到过类似的,用二分搜索,用upper_bound的思想,注意除零的情况。

    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
            long lo = 0;
            long hi = 0;
            for (int e : L) {
                if (hi < e) {
                    hi = e;
                }
            }
            
            hi++;
            while (lo < hi) {
                long mid = (lo + hi) / 2;
                if (mid == 0) {
                    return 0;
                }
                long tryK = pieces(L, mid);
                if (tryK >= k) {
                    lo = mid + 1;
                } else {
                    hi = mid;
                }
            }
            
            return lo - 1;
        }
        
        long pieces(vector<int>& L, long len) {
            int count = 0;
            for (int e : L) {
                count += e / len;
            }
            return count;
        }
    };
    
  • 相关阅读:
    冲刺进度条03
    冲刺进度条02
    冲刺进度条01
    第二阶段团队冲刺(九)
    第二阶段团队冲刺(八)
    第二阶段团队冲刺(七)
    用户体验评价
    第二阶段团队冲刺(六)
    程序员修炼之道:从小工到专家阅读笔记01
    2019春季学期进度报告(十三)
  • 原文地址:https://www.cnblogs.com/lailailai/p/4804569.html
Copyright © 2011-2022 走看看