169. Majority Element

来源:互联网 发布:微信矩阵 编辑:程序博客网 时间:2024/06/11 06:32

题意: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.

思路:其实方法有很多,直接sort求第n/2位的数也可以,但是时间复杂度比较高,可以用字典当做hash table:

class Solution(object):    def majorityElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        d = {}        for i in nums:            if i not in d.keys():                d[i] = 1            else:                d[i] += 1            if d[i] > len(nums)/2:                return i

或者用个投票的方法:

class Solution(object):    def majorityElement(self, nums):        """        :type nums: List[int]        :rtype: int        """        cnt = 0        for i in nums:            if not cnt:                major = i                cnt = 1            elif i != major:                cnt -= 1            else:                cnt += 1        return major
0 0
原创粉丝点击