[Leetcode] 169. Majority Element

limelimejiwon·2022년 3월 7일
0

📄 Description

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums = [3,2,3]
Output: 3

🔨 My Solution

  • use Dictionary for counting the frequency of number in the array
# dictionary for counting the elements
cnt_nums = {}

# count each element
for n in nums:
	if n not in cnt_nums.keys():
    	cnt_nums[n] = 1
    else:
    	cnt_nums[n] += 1
  • get the majority element(key) from the dictionary using the value
return max(cnt_nums, key=cnt_nums.get)

💡 What I learned

How to get key that has min/max value

  1. using di.get
max(list, key=list.get)
  • di.get normally used like di.get(key) and it returns the value for the specific key.
  1. using list comprehension
[k for k,v in list.items() if max(list.values())==v]

💻 My Submission

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        cnt_nums = {}
        for n in nums:
            if n not in cnt_nums.keys():
                cnt_nums[n]=1
            else:
                cnt_nums[n]+=1
        return max(cnt_nums, key=cnt_nums.get)

References
https://leetcode.com/problems/majority-element/

profile
Make your lives Extraordinary!

0개의 댓글