问题
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素
例子
思路
- 哈希表 O(n) O(n)
利用hash表存储每个元素的count。看哪个元素的count>(int)(len/2)
优化:可直接在存的时候,就看其count是否满足条件
- 投票法 O(n) O(1)
在一个游戏中,分了若干个队伍,有一个队伍的人数超过了半数。所有人的战力都相同,不同队伍的两个人遇到就是同归于尽,同一个队伍的人遇到当然互不伤害。这样经过充分时间的游戏后,最后的结果是确定的,一定是超过半数的那个队伍留在了最后。
寻找数组中超过一半的数字,其他数字出现次数的总和都是比不上这个数字出现的次数 。
即如果把 该众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,和是大于 0 的。
代码
//哈希表
class Solution {
public int majorityElement(int[] nums) {
int limit=(int)(nums.length/2);
int res = -1;
Map<Integer,Integer> map = new HashMap<>();
for (int n:nums) {
map.put(n,map.getOrDefault(n,0)+1);
if (map.get(n)>limit)
res = n;
}
return res;
}
}
//投票法
class Solution {
public int majorityElement(int[] nums) {
int target=nums[0], count=1;
for (int i=1; i<nums.length; i++) {
if (target==nums[i]) count++;
else{//target!=count
if (count==0){
target=nums[i];
count=1;
}else//count!=0
count--;
}
}
return target;
}
}
#哈希表
class Solution:
def majorityElement(self, nums: List[int]) -> int:
d = dict()
res = -1
limit = int(len(nums)/2)
for n in nums:
d[n]=d.get(n,0)+1
if d[n]>limit:
res=n
return res
#投票法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count=1
target=nums[0]
for n in nums[1:]:
if target==n:
count+=1
else:
if count!=0:
count-=1
else:
target=n
count=1
return target