您的位置:首页 > 其它

找出数组中出现次数最多的数字

2012-11-17 23:51 423 查看
package cc;
//找出数组{ 3, 4, 1, 5, 3, 1, 4, 5, 4, 3 }中出现次数最多的数字
//1 建立一个新数组,长度与原数组一致,然后将每个数字出现的次数存入此数组
//2 找出此数组中的最大值,尤其关注的是此最大值的下标
public class ArrayCount {
public static void main(String[] args) {
int test[] = new int[] { 1, 2, 3, 2, 3, 3 };
Arr arr = new Arr();
System.out.println("出现次数最多的数字是:" + arr.getMax(test));
}
}

class Arr {
public int getMax(int a[]) {
int count[] = new int[a.length];// 建立一个新数组,长度与原数组一致
for (int x = 0; x < a.length; x++) {// 将每个数字出现的次数存入一个数组
int tempCount = 0;
for (int y = 0; y < a.length; y++) {
if (a[y] == a[x]) {
tempCount++;
}
}
count[x] = tempCount;
}
int tempMax = count[0];// 找出最大值即谁出现次数最多
int maxLocal = 0;
for (int x = 0; x < count.length - 1; x++) {
if (tempMax < count[x + 1]) {
tempMax = count[x + 1];
maxLocal = x + 1;
} else {
tempMax = count[x];// 这个else可有可无
}
}
return a[maxLocal];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐