• 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 }; 
  • 相关阅读:
    C++ string用法
    C++ 静态变量及函数的生命周期
    C++ const的用法和作用
    C++ 指针和引用的区别
    C++ struct 和 Class的区别
    C++对象模型-构造函数语意学
    大端模式与小端模式、网络字节顺序与主机字节顺序
    Spring Boot系列——Spring Boot如何启动
    分库分表利器——sharding-sphere
    并发和多线程-八面玲珑的synchronized
  • 原文地址:https://www.cnblogs.com/NirobertEinteson/p/12583995.html
Copyright © 2020-2023  润新知