LeetCode Majority Element

BabbleDay posted @ 2015年7月16日 17:15 in 刷题防身 with tags python leetcode Majority Element , 404 阅读

利用此题中众数次数超过一半的特性 O(n)

 

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def majorityElement(self, nums):
        count, temp = 1, nums[0]
        for x in nums[1:]:
            if x==temp:
                count += 1
            else:
                count -= 1
            if count==0:
                temp = x
                count = 1
        return temp

哈希表 O(n)


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter