LC.P3115[质数的最大距离]

方法一:遍历

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
class Solution {
public int maximumPrimeDifference(int[] nums) {
int n = nums.length, left = 0, right = 0;
for (int i = 0; i < n; ++i) {
if (isPrime(nums[i])) {
left = i;
break;
}
}
for (int i = n - 1; i >= 0; --i) {
if (isPrime(nums[i])) {
right = i;
break;
}
}
return right - left;
}

private boolean isPrime(int x) {
if (x < 2) return false;
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) return false;
}
return true;
}
}
  • 时间复杂度:$O(n \sqrt M)$,其中$M$为nums中的最大值
  • 空间复杂度:$O(1)$