我的个人微信公众号:Microstrong
微信公众号ID:MicrostrongAI
微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!
知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities
169. Majority Element
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.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
解题思路
(1) 方法一: 快排(Time Limit Exceeded)
# 方法一: 快排
def majorityElement(self, nums: List[int]) -> int:
# 快排
nums = self.quickSort(nums, 0, len(nums) - 1)
# 直接返回中位值
return nums[len(nums) // 2]
def quickSort(self, nums, low, high):
if low < high:
index = self.partition(nums, low, high)
self.quickSort(nums, low, index - 1)
self.quickSort(nums, index + 1, high)
return nums
def partition(self, nums, low, high):
key = nums[low]
while low < high:
while low < high and nums[high] >= key:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] <= key:
low += 1
nums[high] = nums[low]
nums[high] = key
return high
(2)方法二:基于Partition函数的时间复杂度为O(n)算法(Time Limit Exceeded)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
middle = len(nums) // 2
index = self.partition(nums, 0, len(nums) - 1)
while index != middle:
if index > middle:
index = self.partition(nums, 0, index - 1)
else:
index = self.partition(nums, index + 1, len(nums) - 1)
return nums[middle]
def partition(self, nums, low, high):
key = nums[low]
while low < high:
while low < high and nums[high] >= key:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] < key:
low += 1
nums[high] = nums[low]
nums[high] = key
return high
(3)方法三:用字典统计(Accepted)
# 方法三:用字典统计
def majorityElement3(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dic = {}
for i in nums:
if i in dic.keys():
dic[i] += 1
if dic[i] > (len(nums) // 2):
return i
else:
dic[i] = 1
相似题目
【1】牛客网在线编程专题《剑指offer-面试题29》数组中出现次数超过一半的数字,地址:https://blog.csdn.net/program_developer/article/details/102315586
【2】算法-在有序数组、无序数组中进行折半查找和二分法找无序数组中第k小(大)的数,地址:https://blog.csdn.net/program_developer/article/details/80348077
来源:oschina
链接:https://my.oschina.net/u/4285706/blog/4284346