LeetCode/Top150Interview/169MajorityElement.py
2023-06-26 16:39:03 -07:00

37 lines
1.5 KiB
Python

# def majorityElement(nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# majority = {}
# # Start initial position
# for i in range(len(nums)):
# k = 1
# if nums[i] in majority:
# # print(f'found {nums[i]} already')
# continue
# # Count the duplicates
# for j in range(i+1, len(nums)):
# if nums[i] == nums[j]:
# k += 1
# majority[nums[i]] = k
# print(majority)
# # print(max(majority.values()))
# # print(max(majority.items(), key=lambda x: x[1])[0])
# return max(majority.items(), key=lambda x: x[1])[0]
# majorityElement([2,2,1,1,1,2,2])
# Faster runtime and less memory
def majorityElement(nums):
majority = {} # Create an empty dictionary to store the counts of each number
for num in nums: # Iterate over each element in the input list
if num in majority: # Check if the number is already in the dictionary
majority[num] += 1 # If it is, increment its count by 1
else:
majority[num] = 1 # If it is not, add it to the dictionary with a count of 1
if majority[num] > len(nums) / 2: # Check if the count of the number exceeds half the length of the list
return num # If it does, return the number as the majority element
return None # If no majority element is found, return None
result = majorityElement([2, 2, 1, 1, 1, 2, 2]) # Call the function with the input list [2, 2, 1, 1, 1, 2, 2]
print(result) # Print the result