leetcode-5281.使結果不超過閾值的最小除數(Find the Smallest Divisor Given a Threshold)
題目
給你一個整數數組 nums 和一個正整數 threshold ,你需要選擇一個正整數作爲除數,然後將數組裏每個數都除以它,並對除法結果求和。
請你找出能夠使上述結果小於等於閾值 threshold 的除數中 最小 的那個。
每個數除以除數後都向上取整,比方說 7/3 = 3 , 10/2 = 5 。
題目保證一定有解。
示例 1:
輸入:nums = [1,2,5,9], threshold = 6
輸出:5
解釋:如果除數爲 1 ,我們可以得到和爲 17 (1+2+5+9)。
如果除數爲 4 ,我們可以得到和爲 7 (1+1+2+3) 。如果除數爲 5 ,和爲 5 (1+1+1+2)。示例 2:
輸入:nums = [2,3,5,7,11], threshold = 11
輸出:3示例 3:
輸入:nums = [19], threshold = 5
輸出:4提示:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-the-smallest-divisor-given-a-threshold
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路
首先最容易想到的是暴力破解算法,枚舉除數k,從k=1開始枚舉,每次k++,對每個除數,計算,第一個滿足sum<threshold的k即爲答案,不過數據量大,暴力算法會超時。
class Solution {
public:
int smallestDivisor(vector<int>& nums, int threshold) {
int n = 0;
int sum = 0;
do {
n++;
sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += ceil(1.0 * nums[i] / n);
}
}
while(sum > threshold);
return n;
}
};
設,注意到是一個非嚴格單調遞減的離散函數(除數爲正整數),有序可以使用二分法快速搜索符合條件的除數。
下面代碼使用二分搜索算法查找,和二分查找具體某數略有不同,這裏滿足f(k) < threshold
的k可能有多個,要找最小的那個k。下面代碼的註釋和圖幫助理解這個二分查找的實現細節。
二分查找不斷縮小待查找區間,當 l- r == 1
時,出現以下三種情況,可以具體分析便於正確實現算法
class Solution {
public:
int f(int k, vector<int>& nums) {//f(k),非嚴格單調遞減
int s = 0;
for (int i = 0; i < nums.size(); i++) {
s += ceil(1.0 * nums[i] / k);
}
return s;
}
int smallestDivisor(vector<int>& nums, int threshold) {
int l = 1, r = 1e6+10;
int mid = 0;
while (l < r) {
mid = (l + r) / 2;
//if (f(mid, nums) == threshold) return mid;//不能直接返回,可能有多個mid,使得f(mid, nums) == threshold
if (f(mid, nums) > threshold) {
l = mid + 1;//f(mid+1)<=threshold,[l,r]任然包含待搜尋答案
}
else {
r = mid;//剛開始寫成r=mid-1,可能會跳過待搜索答案
}
}
return l;
}
};