数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:map
直接遍历list,然后利用map统计每个数字出现的次数。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
map = {}
for num in nums:
if num in map:
map[num] += 1
else:
map[num] = 1
if map[num] > len(nums) / 2:
return num
return 0
思路2:排序
应为超过数量一半的数,在list排序后,中位数一定是它。所以直接排序后取出来就行了。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2]
思路3:摩尔投票
class Solution:
def majorityElement(self, nums: List[int]) -> int:
x = nums[0]
score = 0
for num in nums:
if score == 0:
x = num
if x == num:
score -= 1
else:
score += 1
return x