在数组中找到最常见的元素并返回新数组

时间:2018-11-13 21:29:45

标签: java arrays

我正在尝试编写一种方法:static int[] moreCommon (int[] a)

方法moreCommon接受一个int数组作为其唯一参数,并且它返回一个整数数组(具有适当的长度),该数组包含所有具有最大频率的值。

例如:

if a={1, 16, 10, 4, 16, 5, 16} it returns {16};    
if a={1, 16, 10, 1, 16, 1, 16} it returns {1,16};
if a=null it returns null;
if a={} it returns {}

2 个答案:

答案 0 :(得分:0)

这是该练习的一种解决方案,尽管您可能无法使用它,甚至无法理解它,因为它使用了您可能尚未了解的Java功能,例如varargs,流和方法引用。 >

static int[] moreCommon(int... a) {
    if (a == null || a.length == 0)
        return a;
    return Arrays.stream(a).boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            // here we have Map<Integer, Long> mapping value to frequency
            .entrySet().stream()
            .collect(Collectors.groupingBy(Entry::getValue, TreeMap::new,
                        Collectors.mapping(Entry::getKey, Collectors.toList())))
            // here we have TreeMap<Long, List<Integer>> mapping frequency to list of values
            .lastEntry().getValue().stream()
            // here we have Stream<Integer> streaming most frequent values
            .mapToInt(Integer::intValue).sorted().toArray();
}

测试

System.out.println(Arrays.toString(moreCommon(1, 16, 10, 4, 16, 5, 16)));
System.out.println(Arrays.toString(moreCommon(1, 16, 10, 1, 16, 1, 16)));
System.out.println(Arrays.toString(moreCommon(null)));
System.out.println(Arrays.toString(moreCommon()));

输出

[16]
[1, 16]
null
[]

答案 1 :(得分:0)

我已尝试根据您的知识为您提供答案,根据示例,最大数量为16,这个想法是用16个数字0填充数组,我们将使用索引,我们将通过该数组,在第一次迭代中,index的值将为1,然后对于每次迭代,我们将询问数字数组中是否存在该值,如果存在,我们将+1添加到我们的16个数字数组中,值0 ,表示此过程将用与索引匹配的数组编号的重合次数替换值0, 您只需要完成编码,即可返回最重复的数字,即null或什么也不返回。如果有必要,我可以完成编码,但是重要的是,您了解该过程并开始使用循环,问候语和您告诉我的任何内容。

public class main {

    static Integer [] numeros = {1,2,1,3,4,4};
    static Integer[] arr = Collections.nCopies(16, 0).toArray(new Integer[0]);

    public static void main(String[] args) {

        for (int i = 1; i <arr.length ; i++) {
            for (int j = 0; j <numeros.length ; j++) {
                if(i<numeros.length){
                    if(numeros[j] == i){
                        arr[i]=arr[i]+1;
                    }
                }
            }
        }
        for (int i = 1; i <arr.length ; i++) {
            System.out.println("count of  numbers " + i + " :  "  + arr[i]);
                 }
             }
        }

输出:

count of  numbers 1 :  2
count of  numbers 2 :  1
count of  numbers 3 :  1
count of  numbers 4 :  2
........
.....
...