【问题标题】:Two Dimensional Matrix as Input二维矩阵作为输入
【发布时间】:2014-04-10 17:37:16
【问题描述】:

如何将二维矩阵写为输入并确定矩阵中出现次数最多的数字。

示例输入: 2 // 行数 3 // 列数 1 2 3 2 3 3 // 这里作为输入的矩阵是 2 x 3 矩阵。其余六个数字是特定矩阵的值。 (第一行的元素是 1 2 3,第二行的元素是 2 3 3)

示例输出:3

import java.util.*;

class ArrayOccurence
{
   public static void main(String args[])
   {
      Scanner sc = new Scanner(System.in);
      int row = sc.nextInt();
      sc.nextLine();
      int column = sc.nextInt();
      sc.nextLine();
      int element = 0;
      int occurence = 0;
      int arr[][] = new int[row][column]; // size of the array
      for(int i=0; i < row; i++)
      {
         for(int j=0; j < column ; j++)
            arr[i][j] = sc.nextInt();
      }
      //Do not modify the code above
      /* Enter your code here */
      // Do not modify code below
      System.out.println("Matrix element "+element+" occurs "+occurence+" times in the     matrix");
   }
}

【问题讨论】:

  • 你是对的兄弟,但我该怎么做才能有人给我提示..!
  • 我建议遍历矩阵并计算唯一元素。你如何做到这一点是练习的重点。我的第一直觉是使用地图。
  • 谢谢大家,你们的建议对我帮助很大..!!!

标签: java arrays matrix


【解决方案1】:

用以下内容替换您的 Enter your code here 行:

    ArrayList<Integer> a = new ArrayList<Integer>();
    int oc = 0;
    int number = 0;

    for(int i=0; i < row; i++)
    {
        for(int j=0; j < column ; j++){
            if(a.isEmpty()){
                a.add(arr[i][j]);
            }
            else if(a.contains(arr[i][j])){

                int temp=0;
                for(int k=0; k<a.size(); k++){
                    if(a.get(k) == arr[i][j]){
                        temp++;
                    }
                }
                if(temp > oc){
                    number = arr[i][j];
                    oc = temp;
                }

                a.add(arr[i][j]);
            }
            else{
                a.add(arr[i][j]);
            }
        }

    }

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您可以再次使用双循环来计算每个数字的出现次数:

    for(int i=0; i < row; i++)
    {
    for(int j=0; j < column ; j++)
    //count occurences with a HashMap<Integer,Integer> or something like that
    }
    

    循环进入您的 HashMap 以找到出现次数最多的一个..

    【讨论】: