原题
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例1:
输入: [3,2,3] 输出: 3
示例2:
输入: [2,2,1,1,1,2,2] 输出: 2
解法
- 解法一:哈希表记录每个元素的出现次数
class Solution {
public int majorityElement(int[] nums) {
int length = nums.length;
Map<Integer,Integer> map = new HashMap<>();
for(int i:nums){
int newer = map.getOrDefault(i,0)+1;
if(newer>length/2) return i;
map.put(i,newer);
}
return 0;
}
}
- 解法二:摩尔投票
func majorityElement(nums []int) int {
votes := 0
head := nums[0]
for index, num := range nums{
if num == head{
votes ++
} else{
votes--
}
if votes == 0{
return majorityElement(nums[index+1:])
}
}
return head
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode169-%e5%a4%9a%e6%95%b0%e5%85%83%e7%b4%a0/