[LeetCode] 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.

Solution:  use dictionary


class Solution:
    # @param num, a list of integers
    # @return an integer
    def majorityElement(self, num):
        myDict = {}
        for i in num:
            if i not in myDict.keys():
                myDict[i] = 1
            else:
                myDict[i] += 1
        for key, value in myDict.items():
            if value > len(num)/2:
                return key


你可能感兴趣的:(LeetCode,python)