題目
給定一個(gè)整數(shù)數(shù)組nums 和一個(gè)整數(shù)threshold ,我們將選擇一個(gè)正整數(shù)除數(shù)并將所有數(shù)組除以它,并將除法的結(jié)果相加。找到最小除數(shù),使得上述結(jié)果小于或等于threshold 。
除法的每個(gè)結(jié)果都四舍五入到大于或等于該元素的最接近的整數(shù)。(例如:7/3 = 3 和 10/2 = 5)。
保證會(huì)有答案。
示例 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
示例 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
示例 3:
Input: nums = [19], threshold = 5
Output: 4
約束:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
題意
給定一個(gè)除求和募捐的值,求一個(gè)募捐這個(gè)中小數(shù)的商人和以慈善事業(yè)的價(jià)值。
思路
因?yàn)橹涤蚬潭ǎ梢杂枚址▕A出答案。
代碼實(shí)現(xiàn)
爪哇
class Solution {
public int smallestDivisor(int[] nums, int threshold) {
int left = 1, right = 1000000;
while (left < right) {
int mid = (right - left) / 2 + left;
int sum = 0;
for (int num : nums) {
sum += Math.ceil(1.0 * num / mid);
}
if (sum <= threshold) {
right = mid;
} else {
left = mid + 1;
}
}
return right;
}
}
|