Java 打印最大频繁元素 公共类TestClass{ 私有静态int maxOccurrence(int a[]{ int max=0; 整数计数=0; 对于(int i=0;i
该程序计算数组中每个元素出现的次数;然后,它返回最大值。在我的示例中,程序打印“5”,因为元素“4”出现了5次。如何也可以打印元素?在这种情况下,程序的输出将是“4:5”。[当标记为C#时回答] 这似乎是一个很好的解决方案:Java 打印最大频繁元素 公共类TestClass{ 私有静态int maxOccurrence(int a[]{ int max=0; 整数计数=0; 对于(int i=0;i,java,arrays,Java,Arrays,该程序计算数组中每个元素出现的次数;然后,它返回最大值。在我的示例中,程序打印“5”,因为元素“4”出现了5次。如何也可以打印元素?在这种情况下,程序的输出将是“4:5”。[当标记为C#时回答] 这似乎是一个很好的解决方案: public class TestClass { private static int maxOccurence(int a[]) { int max = 0; int count = 0; for (int i =
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));
}
}
如果需要,请随时寻求帮助。在C#中,您必须将变量声明为int[]a代码>但不是inta[]代码>
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);
}
}
在Java中,您可以编写
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);
}
我们也可以使用如下哈希表来解决这个问题
4:5
import java.util.Hashtable;
公共类Maxocur{
公共静态void main(字符串[]args){
Hashtable=新的Hashtable();
int maxCount=0;
int maxValue=-1;
int a[]={1,3,2,5,3,6,8,8,6,6,7,5,6,4,5,6,4,1,3,2,6,9,2};
for(int i=0;imaxCount){
maxCount=table.get(a[i]);
最大值=a[i];
}
}
System.out.println(maxValue+“:”+maxCount);
}
}
它一开始是用标签“C#”发布的,所以我回答了这个问题,谢谢downvoteI-see。这是有道理的,尽管很奇怪。Downvote已删除。Aaron,告诉我如何使用它,并解释为什么使用它更好,我在谷歌搜索了一下后才找到原因。好吧,但我从未在任何c#post中看到提到Function.identity()。你能告诉我你的函数类的名称空间吗?我想知道这种讨论是否不是因为标签从C#更改为Java而产生的。让我知道。如果您希望保留代码的格式,请将max=Math.max(count,max)
替换为If(count>max){max=count;}
。然后您可以在同一块中记录i
和a[i]
。
4:5
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);
}
}