LeetCode 169 - 多数元素
2026/1/6小于 1 分钟
题目描述
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:nums = [3,2,3]
输出:3
示例 2:
输入:nums = [2,2,1,1,1,2,2]
输出:2
题解
class Solution {
public int majorityElement(int[] nums) {
if(nums.length == 0) return 0;
int max = (int) (nums.length / 2);
int tag = nums[0];
HashMap<Integer,Integer> map = new HashMap<>();
for(int i =0;i<nums.length;i++){
map.put(nums[i],map.getOrDefault(nums[i],0) + 1);
if(map.get(nums[i]) > max){
tag = nums[i];
break;
}
}
return tag;
}
}暴力,hash 表
