forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1283_Find_the_Smallest_Divisor_Given_Threshold
56 lines (46 loc) · 1.32 KB
/
1283_Find_the_Smallest_Divisor_Given_Threshold
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Leetcode 1283: Find the Smallest Divisor Given a Threshold
Detailed video explanation: https://youtu.be/6b_YFPOYJEk
===========================================================
C++:
----
class Solution {
long compute_sum(vector<int>& nums, int x){
long sum = 0;
for(int n: nums)
sum += n/x + (n%x == 0?0:1);
return sum;
}
public:
int smallestDivisor(vector<int>& nums, int threshold) {
int end = 2;
while(compute_sum(nums, end) > threshold) end <<= 1;
int start = end >> 1;
while(start < end){
int mid = start + (end-start)/2;
if(compute_sum(nums, mid) > threshold) start = mid+1;
else end = mid;
}
return start;
}
};
Java:
-----
class Solution {
private long compute_sum(int[] nums, int x){
long sum = 0;
for(int n: nums)
sum += n/x + (n%x == 0?0:1);
return sum;
}
public int smallestDivisor(int[] nums, int threshold) {
int end = 2;
while(compute_sum(nums, end) > threshold) end <<= 1;
int start = end >> 1;
while(start < end){
int mid = start + (end-start)/2;
if(compute_sum(nums, mid) > threshold) start = mid+1;
else end = mid;
}
return start;
}
}