Copy Books
Note:
这道题很有意思,用的是二分法。想法是不停的试错。这个博客主把这个问题说的很清楚 https://xuezhashuati.blogspot.com/2017/03/lintcode-437-copy-books.html
其实二分法的方法可以变化的点很有限,最多变化的就是检查条件。一般难的题都是判断条件复杂或者需要单独写一个函数进行判定。如果用了二分法,如果一般的思维方式比较难以理解,可以考虑试错。
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; } }
posted on 2017-05-28 03:28 codingEskimo 阅读(271) 评论(0) 编辑 收藏 举报