gpt4 book ai didi

java - 如何使用 for 循环查找给定数组中的最大重复数

转载 作者:行者123 更新时间:2023-12-01 07:18:08 25 4
gpt4 key购买 nike

输入:arr[]={4,3,6,6,4,8,1,9,3,6,7,8,6}输出:6 计数 (4)

public static int countmaxDuplicate(int arr[]) {
int maxcount = 0;
int count = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length - 1; j++) {
if (arr[i] == arr[j]) {
count++;
}
if (count > maxcount) {
count = maxcount;
}
}
}

return maxcount;
}

我试图实现此代码以获得最大重复计数,但无法获得解决方案,请建议我如何使用 for 循环获取输出

最佳答案

您的代码中存在一些问题

        for (int j = i + 1; j < arr.length; j++) {

}

还有

        if (count > maxcount) {
maxcount = count;
}

此外,您需要在每个阶段重新初始化count

完整版:

public static int countmaxDuplicate(int arr[]) {
int maxcount = 0;

for (int i = 0; i < arr.length - 1; i++) {
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}

}
maxcount = Integer.max(maxcount, count);
}

return maxcount;
}

您还可以添加 boolean 数组check以避免重复工作

public static int countmaxDuplicate(int arr[]) {
int maxcount = 0;
boolean[]check = new boolean[arr.length];
for (int i = 0; i < arr.length - 1; i++) {
if(check[i]){
continue;
}
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
check[j] = true;
count++;
}

}
maxcount = Integer.max(maxcount, count);
}

return maxcount;
}

或者甚至考虑使用 HahsMap,这样时间复杂度为 O(n)

HashMap<Integer, Integer> count = new HashMap();
for(int i : arr){
count.put(i, count.getOrDefault(count, 0) + 1);
}

int maxCount;
for(int i : count.values()){
maxCount = Integer.max(maxCount, i);
}
return maxCount;

关于java - 如何使用 for 循环查找给定数组中的最大重复数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50756765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com