Skip to content

Commit 7ed0988

Browse files
Update 169. Majority Element.py
1 parent e9d0b99 commit 7ed0988

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

python/easy/169. Majority Element.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
class Solution:
22
def majorityElement(self, nums: List[int]) -> int:
3-
nums_dict = {}
3+
"""
4+
majorityElement returns the element of array nums that appears more than [n / 2] times
5+
nums array (n == nums.length) (1 <= n <= 5 * 104) (-109 <= nums[i] <= 109)
6+
"""
7+
nums_dict = {} #create empty dict
48
for number in nums:
5-
nums_dict.setdefault(number,0)
6-
nums_dict[number] += 1
7-
max_number = max(nums_dict, key = lambda x: nums_dict[x])
9+
nums_dict.setdefault(number,0) #add number in nums to dict set value to 0
10+
nums_dict[number] += 1 #increment value by 1 for each occurrence of nums
11+
max_number = max(nums_dict, key = lambda x: nums_dict[x]) #get key with value of highest increment
812
return max_number

0 commit comments

Comments
 (0)