计算给定数组中的重复元素

时间:2015-06-07 09:21:58

标签: java arrays

如何计算给定数组中的重复元素?请给我任何建议作为此问题的替代方案。

public static void main(String[] args) 
{
    // TODO Auto-generated method stub
    int a[]={1,2,3,1,2,4,4,4,5};
    int c=0;
    for(int i=0;i!='\0';i++)
    {
        c=1;
        for(int k=i+1;k<9;k++)
        {
            if(a[i]==a[k] && a[i]!='\0')
            {
                c++;
               // a[k]='\0';
            }
        }
        if(a[i]!='\0')
        {
            System.out.println("value is"+a[i]+"repeated in"+c);
            System.out.println("\n");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这是另一种不需要单独数据结构的简单方法:

  • 使用Arrays静态方法
  • 对数组进行排序
  • 现在,您可以遍历数组,知道所有重复项将被组合在一起。不应该很难搞清楚....

答案 1 :(得分:0)

another answer

中提取我的代码
public static void main(String[] args) throws Exception {
    int[] a = {1, 2, 3, 1, 2, 4, 4, 4, 5};
    final Counter<Integer> counter = new Counter<>();
    IntStream.of(a).forEach(counter::add);
    IntStream.rangeClosed(1, 5).forEach(i -> {
        System.out.printf("%s has a count of %s%n", i, counter.count(i));
    });
}

public static class Counter<T> {
    final Map<T, Integer> counts = new HashMap<>();

    public void add(T t) {
        counts.merge(t, 1, Integer::sum);
    }

    public int count(T t) {
        return counts.getOrDefault(t, 0);
    }
}

输出:

1 has a count of 2
2 has a count of 2
3 has a count of 1
4 has a count of 3
5 has a count of 1