int 元素 = 数组[0][0]; 整数计数 = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
int tempElement = array[row][col];
int tempCount = 0;
for (int x = 0; x< array.length;x++){
for(int y=0; y<array[x].length;y++){
if(array[x][y] == tempElement){
tempCount++;
}
if(tempCount > count) {
element = tempElement;
count = tempCount;
}
}
}
}
}
System.out.println("The most common height in the terrain is " + element + " it occurs " + count + " times");
这是我迄今为止尝试过的
我在二维数组中给出了数据集的 100 万个元素,我必须使用 java 从该数据集中找到最频繁的元素,我们只允许使用数组
最佳答案
我会将数组展平,然后对其进行排序。然后,您可以遍历数组对元素进行计数,并在每次值更改时检查计数。
int [][] arr = { {1, 2}, {3, 4}, {5, 5}, {1, 3}, {1, 2}};
int [] flatArray = Arrays.stream(arr).flatMapToInt(Arrays::stream).sorted().toArray();
int previousValue = -1;
int findCounter = 0;
int maxFindCounter = -1;
int maxValueFound = -1;
for(int i = 0; i < flatArray.length; i++) {
if(previousValue != flatArray[i]) {
if(findCounter > maxFindCounter) {
maxFindCounter = findCounter;
maxValueFound = previousValue;
}
findCounter = 0;
}
previousValue = flatArray[i];
findCounter ++;
}
System.out.println(maxValueFound + " : " + maxFindCounter);
关于java - 如何找到二维数组中出现次数最多的元素?除了二维数组之外,你不能使用任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107422/