查找众数及中位数
标题:查找众数及中位数 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
1.众数是指一组数据中出现次数量多的那个数,众数可以是多个
2.中位数是指把一组数据从小到大排列,最中间的那个数,如果这组数据的个数是奇数,那最中间那个就是中位数,如果这组数据的个数为偶数,那就把中间的两个数之和除以2,所得的结果就是中位数
3.查找整型数组中元素的众数并组成一个新的数组,求新数组的中位数
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String num = scanner.nextLine(); String[] nums =num.split("\\s+"); Map<Integer,Integer> map = new HashMap<>(); for (String nu :nums){ int nn = Integer.valueOf(nu); if (map.containsKey(nn)){ map.put(nn,map.get(nn)+1); }else { map.put(nn,1); } } int max = 0; for (int mm : map.values()){ if (mm>=max){ max =mm; } } List<Integer> numList =new ArrayList<>(); for (Map.Entry<Integer,Integer> entry :map.entrySet()){ if (entry.getValue()==max){ numList.add(entry.getKey()); } } Collections.sort(numList); if (numList.size()%2!=0){ int result =(numList.size()+1)/2 -1; System.out.println(numList.get(result)); }else { System.out.println((numList.get(numList.size()/2)+numList.get(numList.size()/2-1))/2); } } }