Wood Cut
阿新 • • 發佈:2017-05-28
tmp color ces 開始 n個元素 int blog pan pie
Note:
審題: 註意也有一種情況是: 一共有N個元素,要k個,但有不需要從每一個塊去取, 只需要從其中的一些取。所以這裏end開始應該取最大的element。而且有可能完全取不到,所以start應該從0開始取。剩下的和copy book那道題想法一致。
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; int end = L[0]; for (int i = 0; i < L.length; i++) { if (end < L[i]) { end= L[i]; } } //System.out.println(end + " " + start); while (start + 1 < end) { int mid = start + (end - start) / 2; int tmp = countPiece(L, mid); //System.out.println(tmp + " " + start + " " + end + " " + mid); if(countPiece(L, mid) >= k) { start = mid; } else { end = mid; } } //System.out.println(start + " " + end); if (countPiece(L, end) >= k) { return end; } return start; } private int countPiece(int[] L, int maxlen) { int count = 0; for (int i = 0; i < L.length; i++) { count += L[i] / maxlen; } return count; } }
Wood Cut