Python solution


  • 0
    J

    Python newbie, solution accepted and running @142ms

    class Solution:
        # @param num, a list of integers
        # @return an integer
        def majorityElement(self, num):
    
            myset = list(set(num))
            # get a comma separated list of all members in num
    
            for i in myset:
                c = [val for val in sorted(num) if val == i]
                # count the occurences of a list member within the array
                if len(c) > (len(num)/2):
                    # run the majority check (appears more than n/2 times)
                    print "majority element is:", i
                    return i
                    break

  • 0
    Y

    What is the function of "get a comma separated list of all members in num"? It seemed the input param num is already a list.


  • 0
    T

    118ms

    class Solution:
    # @param num, a list of integers
    # @return an integer
    def majorityElement(self, num):
        num.sort()
        return num[int(len(num)/2)]

  • 0
    C

    int() is not neccessary here


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.