首页 > 解决方案 > 如何在二维数组中找到最常见的元素?除了二维数组,你不能使用任何东西

问题描述

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 从该数据集中找到最常见的元素,我们只允许使用数组

标签: javaarrays2delement

解决方案


我会将数组展平,然后对其进行排序。然后,您可以遍历数组对元素进行计数,并在每次值更改时检查您的计数。

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);

推荐阅读