Copy Books

Note:html

这道题颇有意思,用的是二分法。想法是不停的试错。这个博客主把这个问题说的很清楚 https://xuezhashuati.blogspot.com/2017/03/lintcode-437-copy-books.html函数

其实二分法的方法能够变化的点颇有限,最多变化的就是检查条件。通常难的题都是判断条件复杂或者须要单独写一个函数进行断定。若是用了二分法,若是通常的思惟方式比较难以理解,能够考虑试错。spa

 

public class Solution {
    /**
     * @param pages: an array of integers
     * @param k: an integer
     * @return: an integer
     */
    public int copyBooks(int[] pages, int k) {
        // write your code here
        if (pages == null || pages.length == 0) {
            return 0;
        }
        
        int start = pages[0]; //at least it needs max{pages[i]}
        int end = 0; //at most it needs sum of pages
        for (int i = 0; i < pages.length; i++) {
            end += pages[i];
            if (start < pages[i]) {
                start = pages[i];
            }
        }
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (countCopier(pages, mid) > k) {
                start = mid;
            } else {
                end = mid;
            }
        }
        //System.out.println(start + " " + end);
        
        if (countCopier(pages, start) <= k) {
            return start;
        }
        
        return end;
    }
    
    private int countCopier(int[] pages, int min) {
        int sum = pages[0];
        int copier = 1;
        for (int i = 1; i < pages.length; i++) {
            if (sum + pages[i] > min) {
                copier++;
                sum = 0;
            }
            sum += pages[i];
        }
        return copier;
    }
}
相关文章
相关标签/搜索