LintCode Copy Books

转自:http://blog.csdn.net/wangyuquanliuli/article/details/47403961


Copy Books

Given an array A of integer with size of n( means n books and number of pages of each book) and k people to copy the 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.) Each person have can copy one page per minute. Return the number of smallest minutes need to copy all the books.

您在真实的面试中是否遇到过这个题? 
Yes
样例

Given array A = [3,2,4], k = 2.

Return 5( First person spends 5 minutes to copy book 1 and book 2 and second person spends 4 minutes to copy book 3. )

挑战

Could you do this in O(n*k) time ?


思想:

将分钟数x带入.让k个人,每个人都尽量工作时间接近x,所有人工作完之后看有没有做完全部的,没有的话返回false

分钟数是个切入点,通过二分的方法将分钟数代入,找到刚好能做完的那个点


public int copyBooks(int[] pages, int k) {
		//利用二分的思想
		int l = 0;
		int r = 99999999;
		while (l < r) {
			int mid = (l + r) / 2;
			if (check(mid, pages, k)) {
				r = mid;
			} else
				l = mid + 1;
		}
		return l;

	}


</pre><pre name="code" class="java">public boolean check(int index, int[] pages, int k) {
		int cnt = 0;
		int sum = 0;
		int i = 0;
		while (i < pages.length) {
			//对于K个人,要做的分钟数得小于等于index,让每个人都尽量做的最多.
			if (sum + pages[i] <= index) {
				sum += pages[i++];
			} else if (pages[i] <= index) {
				cnt++;
				sum = 0;
			} else
				return false;
		}
		if (sum != 0)
			cnt++;
		return cnt <= k;
	}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值