/**
* 求众数
* 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
* <p>
* 你可以假设数组是非空的,并且给定的数组总是存在众数。
* <p>
* 示例 1:
* <p>
* 输入: [3,2,3]
* 输出: 3
* <p>
* 解题思路:定义一个集合,遍历数组,将数组放入集合并且记录元素出现的次数,众数是出现次数大于n/2的元素
*/
public class MajorityElement {
public static void main(String[] args) {
int[] arr = {2, 2, 1, 1, 1, 2, 2};
majorityElement(arr);
}
public static int majorityElement(int[] nums) {
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();//定义一个集合
//遍历数组,将数组放入集合并且记录出现的次数
for (int num : nums) {
if (map.get(num) != null) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
//遍历集合
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > nums.length / 2) {
System.out.println(entry.getKey());
return entry.getKey();
}
}
return 0;
}
}
Leetcode.求众数(Java实现)
最新推荐文章于 2023-05-19 16:16:15 发布