438. Copy Books II (Greedy Algorithm + Binary Search 经典题!)

  1. Copy Books II

Given n books( the page number of each book is the same) and an array of integer with size k means k people to copy the book and the i th integer is the time i th person to copy one 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.) Return the number of smallest minutes need to copy all the books.

Example
Given n = 4, array A = [3,2,4], .

Return 4( First person spends 3 minutes to copy book 1, Second person spends 4 minutes to copy book 2 and 3, Third person spends 4 minutes to copy book 4. )

Solution:

  1. Greedy algorithm + Binary Search
    这题跟437. Copy Books很象,思路也是贪婪+二分。不同之处在于437里面,每本书的厚度不一样,而抄写员速度一样,而这题书的厚度都一样,但抄写员抄写速度不一样。
    这题也是问最大值的最小化。因为也是问的时间,所以二分的对象还是时间。但是贪婪算法里面checkValid(times, t, n) 变成了判断给定数组times,给定时间t,问能不能抄完n本书。注意437里面的checkValid(pages, t, k)是判断给定数组pages,给定时间t,问k个人能不能搞定。
    另外,这题的二分的left和right的开始值可以根据抄写员的最慢和最快速度而定。

代码如下:

class Solution {
public:
    /**
     * @param n: An integer
     * @param times: an array of integers
     * @return: an integer
     */
    int copyBooksII(int n, vector<int> &times) {
        int k = times.size();
        int totalTime = 0; 
        int minTime = INT_MAX, maxTime = 0;
        for (int i = 0; i < k; ++i) {
            minTime = min(minTime, times[i]);
            maxTime = max(maxTime, times[i]);
        }
        int left = n * minTime / k;
        int right = n * maxTime / k;

        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (checkValid(times, mid, n)) {
                right = mid;
            } else {
                left = mid;
            }
        }
        
        if (checkValid(times, left, n)) return left;
        else return right;
    }
    
private:
    //given array times, time t,
     is it ok to finish n books in time?
    bool checkValid(vector<int> &times, int t, int n) {
        int copyTime = times[0];
        int count = 0;     //count of books 
        int k = times.size();
        for (int i = 0; i < k; ++i) {
            count += t / times[i]; // the ith guy can copy t/times[i] books
        }

        return count >= n;
    }
};

//input cases:
//1) 100
//[1,2]
//2) 4
//[3,2,4]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值