LeetCode 169 – Python 3 (Week 3 – 02)

Solution 1:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        dic = {}
        
        for num in nums:
            if num in dic:
                dic[num] += 1
            else:
                dic[num] = 1
        
        for v,k in dic.items():
            if k > len(nums)/2:
                return v

Time complexity is O(n). Space complexity is O(n).

Solution 2

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
  
        #The number of majority element is more than n/2. Set the first number as the majority number. Count this number and not this number. When equal, delete this part. Go on...
        index, cnt = 0, 1
        
        for i in range(1,len(nums)):
            if nums[i] == nums[index]:
                cnt += 1
            else:
                cnt -= 1
                if cnt == -1:
                    index = i
                    cnt = 1

                    
        return nums[index]
        

Time complexity is O(n). Space complexity is O(1).

Solution 3

class Solution:
    def majorityElement(self, nums):
        nums.sort()
        return nums[len(nums)//2]

Time complexity is O(nlgn). It is the time to sort array in Python. Space complexity is O(n). Timsort is used.

Leave a comment

Design a site like this with WordPress.com
Get started