注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
問題
There are N items to be printed on receipt, the i-th item has Item[i] characters. A item must be printed on a single line, and can't change the item printing order.
Return the minimum number of character per line C, such that all the items can be printed exactly in L lines
input [1,2,3,4,5,6,7,8,9,10] L =5
Explain
L1 : 1,2,3,4,5
L2: 6,7
L3: 8
L4: 9
L5: 10
我現在寫出來邏輯因該是錯的,但不曉的怎麼改
public static int findMinimumNumber(int[] nums,int K){
int minimum = 0;
int totalNum = 0;
int longest = 0;
// calculate total # of characters
for(int num : nums){
longest = Math.max(longest,num);
totalNum += num;
}
// find the longest word as Left, total # as Right
// binary search, middle value divide totalNum
int l = longest, r = totalNum;
while(l < r){
int mid = l + (r-l)/2;
int line = totalNum / mid;
// compare result to K
// If result < K , update Left = mid+1; otherwise Right = mid;
if(line == K){
mid += K%mid;
minimum = mid;
break;
}
if(line < K){
r = mid-1;
}else{
l = mid;
}
}
return minimum;
} |