如何计算给定数组中的重复元素?请给我任何建议作为此问题的替代方案。
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");
}
}
}
答案 0 :(得分:0)
这是另一种不需要单独数据结构的简单方法:
答案 1 :(得分:0)
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