Wood Cut
Problem:
Analysis:
Binary search, guess the result. If guess value (cut by assumed wood length) >= k, then increase the guess value.
Solution:
Start always satisfy the requirement, so just return start.
Given n pieces of wood with length
L[i]
(integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.Notice
You couldn't cut wood into float length.
If you couldn't get >= k pieces, return
0
.Binary search, guess the result. If guess value (cut by assumed wood length) >= k, then increase the guess value.
Solution:
Start always satisfy the requirement, so just return start.
public class Solution { /* * @param L: Given n pieces of wood with length L[i] * @param k: An integer * @return: The maximum length of the small pieces */ public int woodCut(int[] L, int k) { // write your code here if (L == null || L.length == 0) return 0; int start= 0, end= Integer.MAX_VALUE; while (start+ 1< end) { int mid = start+ (end- start)/2; int temp = helper(L, mid); if (temp >= k){ start = mid; } else { end= mid; } } return start; } private int helper(int[] L, int len) { int res = 0; for (int i = 0 ; i < L.length; i++) { res += L[i] / len; } return res; } }
评论
发表评论