• LintCode-Copy Books


    Given an array A of integer with size of n( means n books and number of pages of each book) and k people to copy the book. You must distribute the continuous id books to one people to copy. (You can give book A[1],A[2] to one people, but you cannot give book A[1], A[3] to one people, because book A[1] and A[3] is not continuous.) Each person have can copy one page per minute. Return the number of smallest minutes need to copy all the books.

    您在真实的面试中是否遇到过这个题? 
    Yes
    例子

    Given array A = [3,2,4], k = 2.

    Return 5( First person spends 5 minutes to copy book 1 and book 2 and second person spends 4 minutes to copy book 3. )

    挑战

    Could you do this in O(n*k) time ?

    分析:仅仅会O(n*lgM),M为全部数的总和,能够看到,求最小要多少分钟。也就是大于这个数,都是能够的。而小于这个数则都是不能够的。于是能够利用二分来找到这个点
    代码:
    class Solution {
    public:
        /**
         * @param pages: a vector of integers
         * @param k: an integer
         * @return: an integer
         */
        int copyBooks(vector<int> &pages, int k) {
            // write your code here
            int l = 0;
            int r = 99999999;
            while(l<r)
            {
                int mid = (l+r)/2;
                if(check(mid,pages,k))
                {
                    r = mid;
                }
                else
                    l = mid+1;
            }
            return l;
            
        }
        bool check(int index,vector<int>& pages,int k)
        {
            int cnt = 0;
            int sum = 0;
            int i = 0;
            while(i<pages.size())
            {
                if(sum+pages[i]<=index)
                {
                    sum+=pages[i++];
                }
                else if(pages[i]<=index)
                {
                    cnt++;
                    sum = 0;
                }
                else
                    return false;
            }
            if(sum!=0)
                cnt++;
            return cnt<=k;
        }
    };
    


  • 相关阅读:
    (转)SQL Server索引进阶第四篇:页和区
    (转)SQL Server索引进阶第五篇:索引包含列
    CentOS虚拟化服务的配置(转)
    ubuntu 9.04安装xen(转)
    Linux的mount命令详解
    Linux环境下高级文件系统(转)
    安装和使用xenshell(转)
    (转)介绍ice 代理 不错的文章
    mapreduce介绍
    (转)Ubuntu Server Editon 时区设置
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6854781.html
Copyright © 2020-2023  润新知