LeetCode 1283. Find the Smallest Divisor Given a Threshold - 二分查找(Binary Search)系列题23

Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

The test cases are generated so that there will be an answer.

Example 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 of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). 

Example 2:

Input: nums = [44,22,33,11,1], threshold = 5
Output: 44

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 1 <= nums[i] <= 106
  • nums.length <= threshold <= 106

同类型的题有:

 LeetCode 1760. Minimum Limit of Balls in a Bag ,LeetCode 875. Koko Eating Bananas

题目大意:给定一个整数数组nums和一个阈值threshold。任意选择一个正整数作为除数,把数组里每个数都除以它,然后把除的结果都加起来,现在问要使得总和不超过阈值threshold的最小的除数是多大。另外题目要求除法是向上取整。

解题思路:很显然最小的除数就是1;最大除数是数组里的最大的个数(不需要判断更大的数,因为向上取整相除结果都一样全是1)。题目就变成了从[1,maxNum]区间里找到一个最小的数使得相除后结果总和不超过阈值。

取中点值mid=(left+right)//2把区间分成左右两个区间,计算除数为mid时相除后的总和,当总和小于等于阈值时,可以继续在左半区间查找看看有没有更小的值满足条件的数;当总和大于阈值时,则需要在右半区间查找更大的满足条件的数。

class Solution:
    def smallestDivisor(self, nums: List[int], threshold: int) -> int:
        l, r = 1, max(nums)
        
        while l <= r:
            mid = (l + r) // 2
            res = 0
            for num in nums:
                res += (num - 1) // mid + 1
            if res <= threshold:
                r = mid - 1
            else:
                l = mid + 1
        
        return l

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值