输出出现最多的数
package com.fonxian.findmax;
/*
问题:
在一个由自然数1-1000中某些数字所组成的数组中,每个数字可能出现零次或者多次。
设计一个算法,找出出现次数最多的数字。
*/
public class FindMax {
static int findMax(int[] a,int n){
int num;//a中的元素,temp的下标
int max = 0;
int[] temp = new int[1000];
//将数组中的元素设为0,意为出现0次
for(int i = 0;i<1000;i++)
temp[i] = 0;
//a数组中的元素转换为temp数组的下标,temp中的元素则为出现的次数
for(int j = 0;j < n;j++){
num = a[j];
temp[num]++;
}
//找到出现次数最多的数
for(int t = 0;t<1000;t++){
if(temp[t]>max)
max = t;
}
return max;
}
public static void main(String[] args) {
int[] a={1,2,3,4,5,4,5,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8};
System.out.println("出现次数最多的数为:"+findMax(a,a.length));
}
}
测试结果
“出现次数最多的数为:8
输出出现次数最多的前三个数
使用选择排序的思想,来找出现次数最多的前三个数
//输出出现次数最多的三个数
int key;//用来保存下标
int j;
int flag=0;//标记用来判断是否满足3个数
int[] number = new int[3];
for(int i = 0;i<1000&&flag!=3;i++){
key = i;
for(j=i;j<1000;j++){
if(temp[j]>temp[key])
key = j;
}
exch(temp,i,key);
number[flag]=key;
flag++;
}
for(int i = 0;i<3;i++)
System.out.println(number[i]);
exch函数
//交换两个数组的值
static void exch(int[] a,int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
测试结果
8
7
5