Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java—计算最常见的元素_Java_Arrays_Algorithm_Element_Counting - Fatal编程技术网

Java—计算最常见的元素

Java—计算最常见的元素,java,arrays,algorithm,element,counting,Java,Arrays,Algorithm,Element,Counting,任务是编写一个计算最常见数字的代码。例如,A[1,2,4,4,4,5,6,7,4]将是4和4计数。 我需要保持代码的简单,因为我只是尝试将代码从算法和数据结构实现到java 我的想法是这样的,但不知怎么的,我从来没有达到最后的条件 public class countingNumbers{ public static void main(String []args){ System.out.print(counting(new int[]{1,1,1,2,3,4,4

任务是编写一个计算最常见数字的代码。例如,
A[1,2,4,4,4,5,6,7,4]
将是
4
4
计数。 我需要保持代码的简单,因为我只是尝试将代码从算法和数据结构实现到java

我的想法是这样的,但不知怎么的,我从来没有达到最后的条件

public class countingNumbers{

     public static void main(String []args){
         System.out.print(counting(new int[]{1,1,1,2,3,4,4,4,4,5,6}));
     }

     public static int counting(int[] x){
         int memory = 0; 
         int counter = 0;
         int mostCommon = 0;
         for(int i = 0; i < x.length-1;i++){
             for(int j = i+1; j < x.length-1; j++){
                 if(x[i] == x[j]){
                     counter = counter +1;

                 }
                 else if(j == x.length-1 && counter >= memory){
                     mostCommon = x[i];
                     memory = counter;
                     counter = 0;


                 }
             }
         }
         return  mostCommon;
     }
}
公共类计数编号{
公共静态void main(字符串[]args){
系统输出打印(计数(新int[]{1,1,1,2,3,4,4,4,5,6}));
}
公共静态整数计数(整数[]x){
int内存=0;
int计数器=0;
int mostCommon=0;
对于(int i=0;i=内存){
mostCommon=x[i];
内存=计数器;
计数器=0;
}
}
}
返回最常见的;
}
}
->提前谢谢你的回答,我很感激。我只是在寻找逻辑,而不是流、api或任何东西。 我试着手工编写代码,用java实现只是为了我自己看看是否成功,但不幸的是没有成功

更新-正确的解决方案是:

公共类计数数{

 public static void main(String []args){
     System.out.print(counting(new int[]{1,2,2,2,6,2}));
 }

 public static int counting(int[] x){
     int memory = 0; 
     int counter = 1;
     int mostCommon = 0;
     for(int i = 0; i < x.length;i++){
         for(int j = i+1; j <= x.length-1; j++){
             if(x[i] == x[j]){
                 counter = counter + 1;

             }
             if(j == x.length-1 && counter >= memory){
                 mostCommon = x[i];
                 memory = counter;
                 counter = 1;


             }
         }counter = 1;
     } return memory;


 }
publicstaticvoidmain(字符串[]args){
系统输出打印(计数(新int[]{1,2,2,2,6,2}));
}
公共静态整数计数(整数[]x){
int内存=0;
int计数器=1;
int mostCommon=0;
对于(int i=0;i

}

我将对数组进行流式处理并将其收集到一个映射中,对每个元素的出现次数进行计数,然后返回计数最高的元素:

/**
 * @return the element that appears most in the array.
 * If two or more elements appear the same number of times, one of them is returned.
 * @throws IllegalArgumentException If the array is empty
 */
public static int counting(int[] x){
    return Arrays.stream(x)
                 .boxed()
                 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                 .entrySet()
                 .stream()
                 .max(Map.Entry.comparingByValue())
                 .map(Map.Entry::getKey)
                 .orElseThrow(() -> new IllegalArgumentException("x must not be empty"));
}

如果您擅长流api。。或者仅仅为了实现教育目标,有一个带有
分组方式的流式解决方案

Integer[] arr = {1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 6};

Map<Integer, Long> map = Arrays.stream(arr)
        .collect(Collectors.groupingBy(o -> o, Collectors.counting()));

Integer common = map.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey).get();

System.out.println(common);
注意:有许多方法可以从与最大值关联的映射中获取关键点。请参见此处以找到最合适的方法:

另外,
if-else
语句可以由java8中的方法替换:

map.merge(number, 1L, (a, b) -> a + b);

请看以下两行:

 for (int j = i + 1; j < x.length - 1; j++) {
j
严格小于
x.length-1
时循环,但只有当
j
正好等于
x.length-1
时才会触发
else。因此,如果
块中有代码,则永远不能点击
else中的代码

另外,你的计数器应该从一开始,因为你正在计算与你正在查看的条目相匹配的条目数,所以你跳过了计算第一个条目。但是,由于你没有在任何地方输出计数器,我想这不是非常相关


因此,要修复代码,请将内部for循环更改为转到
j声明两个变量以保存最常见的数字及其频率:

int mostCommon =Integer.MIN_VALUE;

int highFreq = 0;
我在你的阵列上创建。对于每个元素,再次迭代数组并计算其频率。如果当前计数大于
highFreq
通过将其设置为当前元素并设置
highFreq
当前计数来更新
mostCommon
。例如:

public class countingNumbers{

    public static void main(String[] args) {
        int[] res = counting(new int[]{6, 4, 5, 4, 5, 6, 4, 3, 2});
        System.out.println("most common number is: " + res[0] + " with " + res[1] + " counts");
    }

    public static int[] counting(int[] x) {
        int mostCommon = Integer.MIN_VALUE;
        int highFreq = 0;
        for (int i = 0; i < x.length; i++) {
            int currFreq = 0;
            for (int j = 0; j < x.length; j++) {
                if (x[i] == x[j]) {
                    currFreq++;
                }
            }
            if (highFreq < currFreq) {
                highFreq = currFreq;
                mostCommon = x[i];
            }
        }
        return new int[]{mostCommon, highFreq};
    }
}
公共类计数编号{
公共静态void main(字符串[]args){
int[]res=计数(新的int[]{6,4,5,4,5,6,4,3,2});
System.out.println(“最常见的数字是:“+res[0]+”和“+res[1]+”计数”);
}
公共静态整数[]计数(整数[]x){
int mostCommon=Integer.MIN_值;
int高频=0;
对于(int i=0;i
您能解释一下您试图实现的逻辑吗?如果你的逻辑是错误的,那么完美的实现就没有多大价值;如果您的逻辑是正确的,那么可以将重点放在实现上。
x.length-1
应该是
x.length
。另外,
中的逻辑,如果
可以在内部循环之外,那么这里应该只需要一个带有排序数组的循环。我加上:{1,2,4,4,5,6,4,4}如果再加上一个4,得到内存=5,所以:{1,2,4,4,5,6,4,4,4,4}如果再加三个4,我得到内存=7,得到内存=11;只是真的不知道为什么…数组中任何一个元素的预期范围是多少?我相信OP想知道的是键,而不是值。您的示例之所以有效,是因为有四个
4
s,而
4
恰好是数组中最频繁的元素。因此流与我无关。我只需要弄清楚它是如何与简单的运算符一起工作的。我试过了,但不起作用。有时它会显示正确的数字/正确数量的数字,但如果我将它们放在不同的顺序中,代码根本不起作用。您使用的具体顺序是什么?它几乎起作用了。我采纳了你提到的改变,但我现在遇到了这个问题。我输入:{1,2,4,4,5,6,4,4},得到内存=4,这是正确的。如果我再加一个4,或者说是广义的,如果我把相同的数字加四次以上,结果就不是应该的结果。例如,如果我输入5 x 4,内存=6。如果我放6 x 4,内存是8等等,我只是注意到代码中有一个严重的错误。仅当数组中的最后一个元素与正在计数的当前元素不相同时,才更新
内存
,因为它位于
else if
块中。
int mostCommon =Integer.MIN_VALUE;

int highFreq = 0;
public class countingNumbers{

    public static void main(String[] args) {
        int[] res = counting(new int[]{6, 4, 5, 4, 5, 6, 4, 3, 2});
        System.out.println("most common number is: " + res[0] + " with " + res[1] + " counts");
    }

    public static int[] counting(int[] x) {
        int mostCommon = Integer.MIN_VALUE;
        int highFreq = 0;
        for (int i = 0; i < x.length; i++) {
            int currFreq = 0;
            for (int j = 0; j < x.length; j++) {
                if (x[i] == x[j]) {
                    currFreq++;
                }
            }
            if (highFreq < currFreq) {
                highFreq = currFreq;
                mostCommon = x[i];
            }
        }
        return new int[]{mostCommon, highFreq};
    }
}