LeetCode Majority Element
阿新 • • 發佈:2018-12-23
Problem
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
找到陣列中重複出現次數超過陣列長度⌊ n/2 ⌋ 的元素
Python 實現
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
#
# You may assume that the array is non-empty and the majority element always exist in the array.
#author li.hzh
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
target = len(nums) // 2
if target == 0:
return nums[0]
map = {}
for val in nums:
if val in map:
map[val] += 1
if map[val] > target:
return val
else:
map[val] = 1
def majorityElement_sort(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[len(nums)//2]
print(Solution().majorityElement_sort([8,8,7,7,7]))
分析
給出兩種方法,一種就是利用map儲存值及其對應出現的次數。最直接的想法了。
不過這道題,有個比較巧的思路。就是如果一個元素出現的次數超過一半,那麼排序後,[n/2]位的元素,一定是該元素。我覺得這個可能是出題者的意圖吧。於是有了解法二。