Majority Element Solutions in Python
Number 169
Difficulty Easy
Acceptance 58.8%
Link LeetCode
Solutions
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/majority-element/# Author : penpenps# Time : 2019-07-22from typing import List# Sort nums and pick the (n/2)-th number# Time Complexity: O(nlogn)# Space Complexity: O(n)class Solution:def majorityElement(self, nums: List[int]) -> int:return sorted(nums)[len(nums)//2]
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/majority-element/# Author : penpenps# Time : 2019-07-22from typing import List# Count occurance for each number and find out the one whose occurance more than n/2 times# Time Complexity: O(n)# Space Complexity: O(n)import collectionsclass Solution:def majorityElement(self, nums: List[int]) -> int:m = collections.Counter(nums)n = len(nums)for k,v in m.items():if v >= n/2:return k
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/majority-element/# Author : penpenps# Time : 2019-07-22from typing import List# Randomly pick one to check whether the answer# Time Complexity: Worst: O(infinity) Average: O(n)# Space Complexity: O(1)import randomclass Solution:def majorityElement(self, nums: List[int]) -> int:def occurance(nums, target):return sum(1 if x == target else 0 for x in nums)n = len(nums)while True:index = random.randint(0, n-1)if occurance(nums, nums[index]) >= n / 2:return nums[index]
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/majority-element/# Author : penpenps# Time : 2019-07-22from typing import List# Recursivly divide two half parts and search most occurance number# Time Complexity: O(nlogn)# Space Complexity: O(logn)class Solution:def majorityElement(self, nums: List[int]) -> int:def occurance(nums, left, right, target):return sum(1 if x == target else 0 for x in nums[left:right+1])def helper(nums, left, right):length = right - left + 1if length <= 2:return nums[left]mid = (left+right) // 2leftMaj = helper(nums, left, mid)rightMaj = helper(nums, mid+1, right)if leftMaj == rightMaj:return leftMajleftMajCnt = occurance(nums, left, mid, leftMaj)rightMajCnt = occurance(nums, mid+1, right, rightMaj)return leftMaj if leftMajCnt > rightMajCnt else rightMajreturn helper(nums, 0, len(nums)-1)
Python solution by liuyubobobo/Play-Leetcode
# Source : https://leetcode.com/problems/majority-element/# Author : penpenps# Time : 2019-07-22from typing import List# Boyer-Moore Voting Algorithm, count for one number, if not equal to current number, count minus 1 until ot 0 then try another number# Time Complexity: O(n)# Space Complexity: O(1)class Solution:def majorityElement(self, nums: List[int]) -> int:ans = nums[0]count = 0for n in nums:if count == 0:ans = ncount += 1elif n == ans:count += 1else:count -= 1return ans