查找INT []数组中最流行元素 [英] Find the most popular element in int[] array
本文介绍了查找INT []数组中最流行元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
INT [] A = INT新[10] {1,2,3,4,5,6,7,7,7,7};
我怎么可以写一个方法并返回7?
我要保持它的原生没有列表,地图或其他助手的帮助。
只有数组[]。
解决方案
公众诠释getPopularElement(INT []一)
{
诠释计数= 1,tempCount;
INT流行= a [0];
INT温度= 0;
的for(int i = 0;我≤(则为a.length - 1);我++)
{
TEMP = a [i];
tempCount = 0;
对于(INT J = 1; J<则为a.length; J ++)
{
如果(临时== A [J]。)
tempCount ++;
}
如果(tempCount>计数)
{
流行=温度;
数= tempCount;
}
}
返回受欢迎;
}
希望这对你的作品。
问候
int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers. Only arrays[].
解决方案
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
Hope this works for you.
Regards
这篇关于查找INT []数组中最流行元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文