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

来源:互联网 发布:凤凰系统有线网络 编辑:程序博客网 时间:2024/05/22 10:40
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];}}

原创粉丝点击