LeetCode 2523. Closest Prime Numbers in Range(2025/3/7每日一题)
标题:Closest Prime Number in Range
题目:
Given two positive integers left
and right
, find the two integers num1
and num2
such that:
left <= num1 < num2 <= right
.- Both
num1
andnum2
are prime numbers. num2 - num1
is the minimum amongst all other pairs satisfying the above conditions.
Return the positive integer array ans = [num1, num2]
. If there are multiple pairs satisfying these conditions, return the one with the smallest num1
value. If no such numbers exist, return [-1, -1]
.
Example 1:
Input: left = 10, right = 19 Output: [11,13] Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19. The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19]. Since 11 is smaller than 17, we return the first pair.
Example 2:
Input: left = 4, right = 6 Output: [-1,-1] Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.
Constraints:
1 <= left <= right <= 106
解题思路:本题的难点在如何能快速判断是否为质数。判断n是否为质数,则只需要判断其是否能整除2~sqrt(n)之间的任意一质数即可。为什么只需要判断到sqrt(n)呢?因为如果能整除,期中一个除数必然会落在2~sqrt(n)之间,如果都落在sqrt(n)之外,该数就大于n了。题中要求两个最近的质数,则输出肯定是相邻的两个质数。因此我们需要:
首先遍历left~right中的所有质数
遍历的同时记录相邻两个质数的距离
选取最近的两个质数输出
代码:
class Solution {
private:
vector<int> prim;
public:
bool isPrim(int n) {
for(int i = 0; i < prim.size() && prim[i] * prim[i] <= n; i++){
if (n % prim[i] == 0) return false;
}
prim.push_back(n);
return true;
}
vector<int> closestPrimes(int left, int right) {
vector<int> res(2, -1);
int last = 0, diff = INT_MAX;
for(int i = 2; i <= right; i++){
if (isPrim(i) && i >= left) {
if (last != 0 && i - last < diff) {
diff = i - last;
res = {last, i};
}
last = i;
}
}
return res;
}
};
时间复杂度为O(N*log(N)),不是最优解
还可以用Sieve of Eratosthenes(埃拉托斯特尼筛法)来判断质数,时间复杂度为O(N*log(logN))