topic
Given an integer array nums and a positive integer threshold, you need to choose a positive integer as the divisor, then divide each number in the array by it, and sum the division results.
Please find the smallest divisor that can make the above result less than or equal to the threshold.
Each number divided by the divisor is rounded up, for example, 7/3 = 3 and 10/2 = 5.
The questions are guaranteed to have solutions.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: If the divisor is 1, we can get the sum to be 17 (1+2+5+9).
If the divisor is 4, we get the sum to be 7 (1+1+2+3). If the divisor is 5, the sum is 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
hint:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
answer
Dichotomy:
Taking the maximum and minimum values as both ends, continuously modify mid to obtain the optimal solution.
class Solution {
public:
int smallestDivisor(vector<int>& nums, int threshold) {
int left = 1;
int right = *max_element(nums.begin(),nums.end());
int res = 1;
while(left<=right)
{
int mid = left + ((right-left)>>1);
int cnt = 0;
for(int i:nums)
{
cnt += i/mid + (i%mid!=0);
}
//cout<<left<<"=="<<mid<<"=="<<right<<"==>"<<cnt<<endl;
if(cnt > threshold)
{
left = mid+1;
}
else
{
right = mid-1;
res = mid;
}
}
return res;
}
};