Copy Books II

Posted flagyuri

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Copy Books II相关的知识,希望对你有一定的参考价值。

Description

Given n books and each book has the same number of pages. There are k persons to copy these books and the i-th person needs times[i] minutes to copy a book.

Each person can copy any number of books and they start copying at the same time. What‘s the best strategy to assign books so that the job can be finished at the earliest time?

Return the shortest time.

Example

Example 1:

Input: n = 4, times = [3, 2, 4]
Output: 4
Explanation: 
    First person spends 3 minutes to copy 1 book.
    Second person spends 4 minutes to copy 2 books.
    Third person spends 4 minutes to copy 1 book.

Example 2:

Input: n = 4, times = [3, 2, 4, 5]
Output: 4
Explanation: Use the same strategy as example 1 and the forth person does nothing.
思路:

可以使用二分或者动态规划解决这道题目. 不过更推荐二分答案的写法, 它更节省空间, 思路简洁, 容易编码.

对于假定的时间上限 tm 我们可以使用贪心的思想判断这 k 个人能否完成复印 n 本书的任务: 每个人都在规定时间内尽可能多地复印, 判断他们复印的总数是否不小于 n 即可.

而时间上限 tm 与可否完成任务(0或1)这两个量之间具有单调性关系, 所以可以对 tm 进行二分查找, 查找最小的 tm, 使得任务可以完成.

 

public class Solution {
    /**
     * @param n: An integer
     * @param times: an array of integers
     * @return: an integer
     */
    public int copyBooksII(int n, int[] times) {
        if (n == 0) {
            return 0;
        }
        int left = 0, right = times[0] * n;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (check(n, times, mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
    
    private boolean check(int n, int[] times, int limit) {
        int count = 0;
        for (int i : times) {
            count += limit / i;
        }
        return count >= n;
    }
}

  

以上是关于Copy Books II的主要内容,如果未能解决你的问题,请参考以下文章

LintCode-Copy Books

Copy and Submit II

copy module

LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段

超实用的php代码片段

codeforces - 1249B2 Books Exchange (hard version)