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 and num2 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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值