我有这个任务,找到int [] []数组中最常见的元素,并打印重复的次数和次数。我解决了这个问题。
我的一个朋友说拥有4个for()
是个坏主意,所以我决定尝试对其进行优化以删除一两个,但找不到办法。
所以这里是:
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;
}
}
}
}
我能想到的唯一优化是从当前元素开始计数直到结束。
请给我更多的想法。我能找到的所有答案都是关于一维数组的,它们几乎都是相同的代码。
最佳答案
您可以迭代整个数组并计算映射中每个元素的出现次数。
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)
}
}
现在,获得的只是在地图中找到具有最大值的键。