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.app
原题地址: Majority Elementspa
难度: Easycode
题意: 找出数量超过数组长度一半的值blog
思路1:排序
对数组进行排序, 因为某个值的数量超过数组长度的一半,排序以后,数组中间的值必然是要求的结果ip
代码:element
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return nums[len(nums)/2]
时间复杂度: O(nlog(n)),即排序的复杂度leetcode
空间复杂度: O(1)get
思路2:
遍历数组,进行统计
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ d = {} for num in nums: d[num] = d.get(num, 0) + 1 if d[num] > len(nums) / 2: return num
时间复杂度: O(n)
空间复杂度: O(n)
思路3:
摩尔投票法: 将数组中不一样两个数配成对
代码:
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) count = 1 num = nums[0] for i in range(1, n): if nums[i] == num: count += 1 elif count == 0: num = nums[i] count += 1 else: count -= 1 count = 0 for i in range(n): if nums[i] == num: count += 1 if count > n / 2: return num
时间复杂度: O(n)
空间复杂度: O(1)