怎么找出数组中出现次数最多的一个数

建立一个HashMap,键存储数据,值存储出现的次数;
找出值最大的那个,返回所对应的键。

	public static int findMax(int[] a) {
		if (a.length == 0) {
			return Integer.MAX_VALUE;
		}
		HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
		for (int num : a) {
			if (!hashMap.containsKey(num)) {
				hashMap.put(num, 1);
			} else {
				hashMap.put(num, hashMap.get(num) + 1);
			}
		}

		Set<Integer> keySet = hashMap.keySet();
		int maxTimes = Integer.MIN_VALUE;
		int maxValue = 0;
		for (int key : keySet) {
			if (hashMap.get(key) > maxTimes) {
				maxTimes = hashMap.get(key);
				maxValue = key;
			}
		}

		return maxValue;
	}
发布了58 篇原创文章 · 获赞 0 · 访问量 985

猜你喜欢

转载自blog.csdn.net/Mason97/article/details/104554588