• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Niro Einteson
文可提笔安天下 武可上马定乾坤
博客园    首页    新随笔    联系   管理    订阅  订阅

1283. 使结果不超过阈值的最小除数

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

 

 1 class Solution {
 2 public:
 3 
 4     int smallestDivisor(vector<int>& nums, int threshold) {
 5         //if(nums.size()==0) return 0;// 使用二分查找 
 6         int left=1,right=1000001;//求出里面的最大值,即可//for (int& n: nums) {            r = max(r, n);        }
 7         while(left<right){
 8             int mid=(left+right)>>1;
 9             int sum=0;
10             for(int num:nums){
11                 sum+=num/mid+(num%mid==0?0:1);//for (int& n: nums) sum+= (num + mid - 1) / mid;
12             }
13             if(sum>threshold){
14                 left=mid+1;//除数和 大于阈值, 区间在  [mid+1,right];
15             }
16             else{
17                 right=mid;//除数和 小于阈值,区间在 [left,mid];
18             }
19         }
20         return left;
21     }
22 }; 

 

posted @ 2020-03-27 20:01  Nirogo  阅读(227)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3