leetcode--Majority Element

题目链接:https://leetcode.com/problems/majority-element/

算法类型:分治法

题目分析:获取长度为n的数组中的众数(出现次数大于等于⌊ n/2 ⌋)

代码实现:

class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_len = len(nums)
if nums_len == 1:
return nums.pop()

part_one_majory = self.majorityElement(nums[0: (nums_len / 2)])
part_two_majory = self.majorityElement(nums[(nums_len / 2): nums_len])

if part_one_majory == part_two_majory:
return part_one_majory

count_one = nums.count(part_one_majory)
count_two = nums.count(part_two_majory)
if count_one > count_two:
return part_one_majory
return part_two_majory

posted @ 2016-12-12 11:05  颛顼执锐  阅读(97)  评论(0编辑  收藏  举报