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

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

相关文章:

  • OSI七大模型 --- 发送邮件
  • 操作系统 2.4-内核级线程基本实现原理
  • 小程序和页面生命周期详解
  • 游戏元宇宙崛起:AI代理IP驱动虚拟世界“无限可能”​
  • web3区块链
  • 火绒终端安全管理系统V2.0--纵深防御体系(分层防御)之规则拦截层
  • 深度学习笔记——循环神经网络RNN
  • 2025年Q2(桥门式)起重机司机考试题库
  • 换元积分法的数学本质与几何可视化——一场关于变量代换的数学探秘
  • 深度学习驱动的智能化革命:技术演进与跨行业实践
  • React + React-intl @3.xx + TypeScript
  • DeepSeek系列模型技术报告的阅读笔记
  • 前馈神经网络 - 参数学习(梯度下降法 - 多分类任务)
  • [LeetCode力扣hot100]-堆
  • 笔记本电脑外接固态移动硬盘可以用于深度学习吗
  • echarts的geo3d绘制地图添加定位点和点击事件,发现当有一个散点的时候无法点击
  • 研一控制工程转码,选择后端开发还是嵌入式?嵌软开发需要懂硬件吗?
  • Deepseek 使用攻略
  • 在 IntelliJ IDEA 中使用 JUnit 进行单元测试
  • 【CXX】5.4 属性
  • 辽宁省住房和建设厅官方网站/搜索引擎营销实训报告
  • 长春网站建设开发的有哪些/网络宣传方式有哪些
  • 网上买卖交易平台有哪些/seoul是什么意思
  • 做网站百度收费吗/短链接生成网址
  • 开发购物平台网站费用/百度刷首页怎么刷
  • 用ps做网站的临摹/数据分析系统