知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 169. Majority Element (Easy/Python)

코방코 2022. 10. 5. 23:06
728x90
 

Majority Element - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Above is the link to the problem.

 

Problem

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

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

 

I solved this problem by the below code.

 

 

This code gets the top 2.19% of time efficiency and uses 15.5MB of memory.

 

 

I was surprised to see code with faster runtime than I did.

It was a method of sorting a given list and immediately selecting an element in the middle. 

Because majority elements occupy more than half of the total list length.

This method can be applied just the list is sorted.

nums = [2,2,1,1,1,2,2]
nums.sort #nums = [1,1,1,2,2,2,2]
majority element = nums[len(nums)//2]

 

I was very surprised by their intuition.

I think I should try to look at the problem in a bigger way.

 

728x90
반응형