2016-07-08 8 views
2

私はこのタスクを持っているint [] []配列で最もよく見られる要素を見つけて、繰り返された回数と回数を表示します。問題を解決しました。2次元アレイで最も一般的な要素。最適化する方法は?

私の友人は、4 for()を持つことは悪い考えです。私はそれを最適化して1〜2を削除しようと決心しましたが、方法を見つけられませんでした。

だからここにある:

 int cnt, element = arr[0][0], numberRepeats = 0;//cnt-counter,what's the element ,how many times it's repeated 
    for (int i = 0; i < arr.length; i++) { 
     for (int j = 0; j < arr[i].length; j++) {//those two for's are for the current element 
      cnt = 0;//counter is nullified 
      for (int j2 = i; j2 < arr.length; j2++) { 
       for (int k = 0; k < arr[j2].length; k++) {//and those two are the compared element 
        if (arr[i][j] == arr[j2][k]) {//if the current element is the same as the compared element,increase counter 
         cnt++; 
        } 
       } 

      if (cnt > numberRepeats) {//after the compared element is done comparing and the number of repeats of the current element is more then the lastly checked element 
       element = arr[i][j];//we get the element ,and how many times it's repeated 
       numberRepeats = cnt; 
      } 
     } 
    } 
} 

私は最後まで現在の要素からカウントを開始したと考えることができる唯一の最適化。

もう少し考えてください。私が見つけることができるすべての答えは1D配列のものでしたが、すべて同じコードでした。

答えて

2

マップ全体の配列を繰り返し、マップ内のすべての要素の出現を数えるだけです。

Map<Integer, Integer> elementsCounts = new HashMap<>(); 
for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr[i].length; j++) { 
     Integer count = elementsCounts.get(arr[i][j]]) 
     if(count == null){ 
      count = 0 
     } 
     elementsCounts.put(arr[i][j]], count+1) 
    } 
} 

ここで得られるのは、マップの最大値を持つキーを見つけることです。

+0

だから私は地図が何であるかを学ぶだけです: ありがとうございました:) –

+0

@KostadinKostadinov [地図チュートリアル](https://docs.oracle.com/javase/tutorial/collections/interfaces /map.html)。 –

関連する問題