代码解决
class Solution {
public:// 判断一个数是否为质数bool isPrime(int n) {if (n <= 1) {return false;}if (n <= 3) {return true;}if (n % 2 == 0 || n % 3 == 0) {return false;}for (int i = 5; i * i <= n; i += 6) {if (n % i == 0 || n % (i + 2) == 0) {return false;}}return true;}// 计算数组中质数下标的最大距离int maximumPrimeDifference(vector<int>& nums) {vector<int> primeIndices; // 存储质数的下标int result = 0; // 最大距离的结果// 找出所有质数的下标for (int i = 0; i < nums.size(); i++) {if (isPrime(nums[i])) {primeIndices.push_back(i); // 将质数的下标添加到数组中}}// 如果质数的数量小于2,直接返回0,因为无法计算两个质数的距离if (primeIndices.size() < 2) {return result;}// 计算最大和最小质数下标之间的距离int maxIndex = *max_element(primeIndices.begin(), primeIndices.end());int minIndex = *min_element(primeIndices.begin(), primeIndices.end());result = maxIndex - minIndex;return result;}
};