当前位置: 首页 > article >正文

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


http://www.kler.cn/a/578965.html

相关文章:

  • 中小企业Windows双因素认证的“轻量化”安全解决方案
  • 探索数据仓库自动化:ETL流程设计与实践
  • qt 播放pcm音频
  • 【模板】树算法之LCA(最近公共祖先)
  • Shell编程概述与Shell变量
  • 物联网中设备异构的问题-甚至可以用工业数据采集器?
  • C++之序列容器(vector,list,dueqe)
  • 在运维工作中,Lvs、nginx、haproxy工作原理分别是什么?
  • 【TI】如何更改 CCS20.1.0 的 WORKSPACE 默认路径
  • 开发环境搭建-05.后端环境搭建-前后端联调-通过断点调试熟悉项目代码特点
  • Hot 3D 人体姿态估计 HPE Demo复现过程
  • Excel 粘贴数据到可见单元格
  • 信号的希尔伯特变换与等效基带表示:原理与Matlab实践
  • [数据分享第七弹]全球洪水相关数据集
  • 使用OpenCV和MediaPipe库——实现人体姿态检测
  • 论文阅读方法
  • 2008-2024年中国手机基站数据/中国移动通信基站数据
  • GHCTF2025--Web
  • Windows软件插件-音视频文件读取器
  • 稚晖君级硬核:智元公司开源机器人通信框架AimRT入驻GitCode平台