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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/87631772
  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]

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/87631772