Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2523. Closest Prime Numbers in Range

Rain Hu

2523. Closest Prime Numbers in Range


一、題目

Given two positive integers left and right, find the two integers num1 and num2 such that:

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Sieve of Eratosthenes

vector<int> closestPrimes(int left, int right) {
    // create pre-built table
    vector<int> table(right+1, 0);
    iota(table.begin(), table.end(), 0);
    table[1] = 0;
    for (int i = 2; i <= right; i++) {
        if (table[i] != i) continue;
        for (int j = 2*i; j <= right; j += i) {
            table[j] = i;
        }
    }
    // 遍歷完所有符圍中的質數,回傳距離最小的兩個質數
    stack<int> st;
    int diff = INT_MAX;
    vector<int> res = {-1,-1};
    for (int i = left; i <= right; i++) {
        if (table[i] != i) continue;
        if (!st.empty()) {
            if (i - st.top() < diff) {
                diff = i - st.top();
                res[0] = st.top();
                res[1] = i;
            }
        }
        st.push(i);
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2522. Partition String Into Substrings With Values at Most K
Next
[LeetCode] 520. Detect Capital