-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathSolution.java
More file actions
39 lines (33 loc) · 1013 Bytes
/
Copy pathSolution.java
File metadata and controls
39 lines (33 loc) · 1013 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.*;
class Solution {
private static boolean[] isPrime = new boolean[1000001];
static {
Arrays.fill(isPrime, true);
precompute();
}
private static void precompute() {
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= 1000000; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= 1000000; j += i) {
isPrime[j] = false;
}
}
}
}
public int[] closestPrimes(int left, int right) {
int prev = -1, minDiff = Integer.MAX_VALUE;
int num1 = -1, num2 = -1;
for (int i = left; i <= right; i++) {
if (isPrime[i]) {
if (prev != -1 && (i - prev < minDiff)) {
minDiff = i - prev;
num1 = prev;
num2 = i;
}
prev = i;
}
}
return (num1 == -1) ? new int[]{-1, -1} : new int[]{num1, num2};
}
}