-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet225.cpp
More file actions
39 lines (33 loc) · 1004 Bytes
/
leet225.cpp
File metadata and controls
39 lines (33 loc) · 1004 Bytes
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
class Solution {
public:
vector<int> closestPrimes(int left, int right) {
vector<bool> sieve(right + 1, true);
sieve[0] = sieve[1] = false;
for (int i = 2; i * i <= right; ++i) {
if (sieve[i]) {
for (int j = i * i; j <= right; j += i) {
sieve[j] = false;
}
}
}
vector<int> primes;
for (int i = left; i <= right; ++i) {
if (sieve[i]) {
primes.push_back(i);
}
}
if (primes.size() < 2) {
return {-1, -1};
}
int min_gap = INT_MAX;
vector<int> result = {-1, -1};
for (int i = 1; i < primes.size(); ++i) {
int gap = primes[i] - primes[i - 1];
if (gap < min_gap) {
min_gap = gap;
result = {primes[i - 1], primes[i]};
}
}
return result;
}
};