提取一堆数字中出现次数最多的数字

时间:2023-01-11 11:03:37

算法实现:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FindMaxCountNumber {
    public static Map<Integer, Integer> find(int[] array) {
    	Map<Integer, Integer> map = new HashMap<>();
    	for(int i=0; i<array.length; i++) {
    		if(map.containsKey(array[i])) {
    			int count = map.get(array[i]);
    			map.put(array[i], count + 1);
    		} else {
    			map.put(array[i], 1);
    		}
    	}
    	return map;
    }
    public static void main(String[] args) {
	int[] array = {1,2,3,4,5,6};
	Map<Integer, Integer> map = find(array);
	Collection<Integer> values = map.values();
	int maxCount = Collections.max(values);
	List<Integer> maxNumbers = new ArrayList<>();
	for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
		if(entry.getValue() == maxCount) {
			maxNumbers.add(entry.getKey());
		}
	}
	System.out.print("出现次数最多的数字是:");	
	for(int i=0; i<maxNumbers.size(); i++) {
		System.out.print(maxNumbers.get(i) + " ");
	}
	System.out.println();	
	System.out.println("这些数字都出现" + maxCount + "次");
    }
}