728x90
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
반응형
'Code > LeetCode' 카테고리의 다른 글
[LeetCode] 1833. Maximum Ice Cream Bars (Medium/Python) (0) | 2023.01.08 |
---|---|
[LeetCode] 171. Excel Sheet Column Number (Easy/Python) (0) | 2022.11.16 |
[LeetCode] 168. Excel Sheet Column Title (Easy/Python) (1) | 2022.09.29 |
[LeetCode] 136. Single number (Easy/Python) (0) | 2022.09.26 |
[LeetCode] 125. Valid Palindrome (Easy/Python) (0) | 2022.09.25 |