前言
经过前期的基础训练以及部分实战练习,粗略掌握了各种题型的解题思路。现阶段开始专项练习。
描述
实现原理与步骤
1.8个方便遍历集合组成的数据
2.素数判断,由于数据较为稀疏,当个判断效率更高。
3.根据结果规则返回结果。
实现代码
class Solution {
public int mostFrequentPrime(int[][] mat) {
int row = mat.length;
int col = mat[0].length;
HashMap<Integer, Integer> map = new HashMap();
int[][] direct = { { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 }, { 1, 1 }, { 1, -1 }, { -1, -1 }, { -1, 1 } };
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int[] d : direct) {
//v由于随着该方向延伸动态变化,需要在新的方向搜索时初始化
int v = mat[i][j];
int x = i + d[0];
int y = j + d[1];
while (x >= 0 && x < row && y >= 0 && y < col) {
v = v * 10 + mat[x][y];
if (isPrime(v)) {
map.merge(v, 1, Integer::sum);
}
x += d[0];
y += d[1];
}
}
}
}
int res=-1;
int maxCnt=-1;
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
int v=entry.getKey();
int c=entry.getValue();
if(c>maxCnt){
res=v;
maxCnt=c;
}else if(c==maxCnt){
res=Math.max(res,v);
}
}
return res;
}
public boolean isPrime(int x) {
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
}