目录
1. 题目描述
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素(你可以假设数组是非空的,并且给定的数组总是存在多数元素)。
2. 算法思路
思路:使用哈希表快速统计每个元素出现的次数。
处理:
1)定义一个哈希表来存储数组中每个元素以及出现的次数
2)遍历数组nums中的每一个元素,判断哈希表中是否存在该元素,若存在,将该元素以及出现的次数加入哈希映射中
3)获取哈希表键值对中的value,若value>n/2,则输出对应的key
3. 算法代码
import java.util.HashMap;
import java.util.Map;
/**
* @Author: 张晴晴
* @Date: 2021/12/11
* @Description: 多数元素
*/
public class 多数元素169 {
public static void main(String[] args) {
// int[] nums = {3, 2, 3};
int[] nums = {2, 2, 1, 1, 1, 2, 2};
int element = majorityElement(nums);
System.out.println(element);
}
/**
* 哈希表
*
* @param nums
* @return
*/
public static int majorityElement(int[] nums) {
int len = nums.length / 2; //默认是向下取整的
Map<Integer, Integer> map = new HashMap<>();
for (int i : nums) {
if (map.containsKey(i)) {
Integer num = map.get(i);
num++;
map.put(i, num);
} else {
map.put(i, 1);
}
}
int key = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
if (value > len) {
key = entry.getKey();
}
}
return key;
}
}
4. 时空复杂度分析
哈希表:
时间复杂度:O(n)
空间复杂度:O(n)