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;
        }
    };
    
  • 相关阅读:
    开发入门
    Web开发的四个域
    JSP语法
    JSP入门
    变量的作用范围
    面向对象
    C#编译执行过程
    css3的渐变、背景、过渡、分页
    css3选择器总结
    css3基础选择器
  • 原文地址:https://www.cnblogs.com/lailailai/p/4804569.html
Copyright © 2011-2022 走看看