java - 如何在二维数组中找到最常见的元素?除了二维数组,你不能使用任何东西
问题描述
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);
推荐阅读
- reactjs - 如何将数组值传递给另一个组件?
- botframework - 无法从 Linux Mint 20.2 上的 Azure 门户打开 Bot Framework Composer
- r - 在条件下重建 tibble
- r - 控制图例在 GGplot 中的位置
- html - 如何更改导航栏下拉菜单的背景颜色?
- amazon-web-services - 允许 bash 脚本在 AWS Centos 7 实例中启动时运行
- python - 正态分布->分布函数->Python中的生存函数
- python - 在功能上,torch.multinomial 是否与 torch.distributions.categorical.Categorical 相同?
- android - 使用 RSA OAEP 解密的 Android 上的 MGF1 不支持 SHA-256 摘要?
- javascript - createError.js:16 未捕获(承诺)错误。reactJS到mongodb连接