Wood Cut
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.
考察 Binary Search. 本题是二分搜索可行解。如果 长度len 为可行解那么 1~ len - 1一定是可行解。当 len 不是可行解那么len + 1 ... 一定不是可行解。因此可行解满足二分查找的条件。题目要求的是找到最大可行解,因此是二分搜索最大可行解。
注意:题目没说每一wood都需要使用,因此其解的取值范围为 1 ~ max, 其中max 为L的最大值。
1 public class Solution { 2 public int woodCut(int[] L, int k) { 3 int max = 0; 4 for (int i = 0; i < L.length; i++) { 5 max = Math.max(max, L[i]); 6 } 7 8 int start = 1, end = max; 9 while (start + 1 < end) { 10 int mid = start + (end - start) / 2; 11 if (check(L, mid, k)) { 12 start = mid; 13 } else { 14 end = mid; 15 } 16 } 17 if (check(L, end, k)) { 18 return end; 19 } 20 if (check(L, start, k)) { 21 return start; 22 } 23 return 0; 24 } 25 26 boolean check(int[] A, int len, int k) { 27 int count = 0; 28 for (int i = 0; i < A.length; i++) { 29 count = count + A[i] / len; 30 } 31 if (count >= k) { 32 return true; 33 } else { 34 return false; 35 } 36 } 37 }

浙公网安备 33010602011771号