打印最大频繁元素

时间:2016-01-15 08:38:07

标签: java arrays

public class TestClass {

    private static int maxOccurence(int a[]) {
        int max = 0;
        int count = 0;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] == a[j]) {
                    count++;
                    max = Math.max(max, count);
                }
            }
            count = 0;
        }
        return max + 1;
    }

    public static void main(String[] args) {
        int a[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
        System.out.println(maxOccurence(a));
    }
}

对于数组的每个元素,此程序计算元素出现的次数;然后,它返回最大值。在我的例子中,程序打印&#34; 5&#34;,因为元素&#34; 4&#34;发生5次。如何打印元素?在这种情况下,程序的输出将是&#34; 4:5&#34;。

4 个答案:

答案 0 :(得分:1)

在Java中你可以写

int[] a = {3, 3, 4, 2, 4, 4, 2, 4, 4};
Map<Integer, Long> countMap = IntStream.of(a).boxed()
        .collect(groupingBy(i -> i, counting()));
Map.Entry<Integer, Long> first = countMap.entrySet().stream()
                        .sorted(comparing(Map.Entry<Integer, Long>::getValue).reversed())
                        .findFirst().orElseThrow(AssertionError::new);
System.out.println(first.getKey()+":"+first.getValue());   

打印

4:5      

答案 1 :(得分:0)

[标记为C#时的答案] 这似乎是一个很好的解决方案:

public static class TestClass
{
    public static void PrintMaxOccurence(int[] a)
    {

        var maxOccurenceGroup = a.ToList().GroupBy(s => s)
            .OrderByDescending(s => s.Count())
            .First();

        Console.WriteLine(maxOccurenceGroup.Key + " occured " + maxOccurenceGroup.Count() + " times.");
        Console.ReadKey();
    }
}

class Program
{
    public static void main(String[] args)
    {
        var a = new[] { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
        TestClass.PrintMaxOccurence(a);
    }
}

如果需要,请随时提出帮助。

答案 2 :(得分:0)

在C#中,您必须将变量声明为int[] a;,而不是int a[];

static void Main(string[] args)
{    
    int[] a = new[] { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
    PrintMaxOccurence(a);    
}

private static void PrintMaxOccurence(int[] a)
{    
    var result = (from item in a
            group item by item into x
            orderby x.Count() descending
            select new { Element = x.Key, OccurenceCount = x.Count() }).First();

    Console.WriteLine("{0} : {1}", result.Element, result.OccurenceCount);    
}

答案 3 :(得分:0)

我们也可以使用哈希表解决问题如下。

import java.util.Hashtable;


public class MaxOcurr {

  public static void main(String[] args) {

    Hashtable<Integer,Integer> table = new Hashtable<Integer, Integer>();

    int maxCount = 0;

    int maxValue = -1;

    int a[] = {1,3,2,5,3,6,8,8,8,6,6,7,5,6,4,5,6,4,6,4,1,3,2,6,9,2};

    for (int i = 0; i < a.length; i++) {

      if (table.containsKey(a[i])) {
      table.put(a[i], table.get(a[i])+1);


      } else {
        table.put(a[i],1);
      }


      if (table.get(a[i]) > maxCount) {
        maxCount = table.get(a[i]);
        maxValue = a[i];
      }
    }

    System.out.println(maxValue +":"+ maxCount);

  }

}