力扣 169. 多数元素

暴力hash解法

1
2
3
4
5
6
7
8
9
10
11
def majorityElement(nums):
# 假设只有两个数
save = {}
for num in nums:
if num in save.keys():
save[num] += 1
else:
save[num] = 1

save = {v: k for k, v in save.items()}
return save[max(save.keys())]

摩尔投票法

1
2
3
4
5
6
7
8
9
10
11
12
def majorityElement(nums):
# 假设只有两个数
cand, count = nums[0], 0
for num in nums:
if cand == num:
count += 1
else:
count -= 1
if count == 0:
cand, count = num, 1

return cand
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信