1. 程式人生 > 其它 >leetcode 1283. 使結果不超過閾值的最小除數

leetcode 1283. 使結果不超過閾值的最小除數

給你一個整數陣列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
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

採用二分法,

1:選取1到陣列中最大值作為區間。

2:計算出中間值,當作除數,在陣列中求和。

3:按照二分法的方式,不斷查詢。返回最小值。

    public int smallestDivisor(int[] nums, int threshold) {
        int st = 1;
        int end = 0;
        for (int i : nums) {
            end = Math.max(i, end);
        }
        long min = Integer.MAX_VALUE;
        long c;
        int value = 0;

        while (st <= end) {
            
int m = st + ((end - st) >> 1); long sum = getSum(nums, m); if (sum > threshold) { st = m + 1; } else { end = m - 1; c = threshold - sum; if (c < min || (c == min && value > m)) { min = c; value = m; } } } return value; } private long getSum(int[] arr, int value) { long sum = 0; for (int i : arr) { int j = i / value; if(j * value != i) { sum++; } sum += j; } return sum; }