众数问题
2016-10-06 11:27
344 查看
问题描述:给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数,多重集合S中重数最大的元素称为众数。
例如:S={1,2,2,3,5}.多重集S的众数是2,其重数是3.
解法:
众数
问题描述:输入20个数,每个数都在1-10之间,求1-10中的众数(众数就是出现次数最多的数,如果存在一样多次数的众数,则输出权值较小的那一个)。
例如:S={1,2,2,3,5}.多重集S的众数是2,其重数是3.
解法:
import java.util.*; /** * DateTime: 2016/10/6 07:50 * 功能:众数问题 * 思路: * 1.先对元素进行从小到大的排序 * 2.从第一个元素开始遍历,看他后面有几个与他相等的 * 3.用count变量记录当前元素总共出现几次,max变量记录最大次数,map记录最大次数对应的值 * 4.如果次数大于最大次数,则更新最大次数,并把当前值和最大次数压到map中 * 5.如果次数等于最大次数,并把当前值和最大次数压到map中(因为要考虑到多个数出现的次数一样是要全部输出) * 6.从map中查找value值==max的数输出 */ public class Topic2_1 { public static void main(String[] args) { Scanner in=new Scanner(System.in); int count=in.nextInt(); //输入数字个数 ArrayList arrayList=new ArrayList(); int a; while ( (count--)>0 ){ //输入数据 a=in.nextInt(); arrayList.add(a); } showFun(arrayList); } /** * 众数处理函数 * @param arrayList 多重集S */ public static void showFun(ArrayList arrayList) { Collections.sort(arrayList); //数组排序 int max = 1;//最大次数 Map map = new HashMap(); //存放:当有多个数出现次数相等时 for ( int i = 0; i < arrayList.size(); i++ ) { int count = 1; for ( int j = i + 1; j < arrayList.size() && arrayList.get(i) == arrayList.get(j); j++ ) { //如果当前数等于上一个数 要用是满足两个条件才行 count++; } if ( count > max ) { //当前次数为最大时,更新最大次数 并保存值 max = count; map.put(arrayList.get(i), count); } if ( count == max ) { //当前次数==之前的次数时,保存值 map.put(arrayList.get(i), count); } } for ( Object key : map.keySet() ) { //获得key if ( max == (int) map.get(key) ) { //获得value 如果value==最大次数 则输出 System.out.println("maxNum=" + key + " count=" + max); } } } }
众数
问题描述:输入20个数,每个数都在1-10之间,求1-10中的众数(众数就是出现次数最多的数,如果存在一样多次数的众数,则输出权值较小的那一个)。
/** * 本题存在特殊性 就是输入的数只会是1-10 * 所以可以直接使用数组操作 */ public static void doMain() { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = 20; int[] arr = new int[11]; //因为下标从0开始,而这里的++arr[x] 所以直接定义11位 for (int i = 0; i < n; i++) { int x = in.nextInt(); ++arr[x]; } int max = 1; //从下标1开始遍历 for (int j = 2; j < arr.length; j++) { if(arr[max]<arr[j]) max = j; } System.out.println(max); //下标就是对应的数值 } in.close(); }