-
[LeetCode] 169. Majority ElementAlgorithm/LeetCode 2021. 9. 29. 09:34
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
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Constraints:
- n == nums.length
- 1 <= n <= 5 * 104
- -231 <= nums[i] <= 231 - 1
class Solution: def majorityElement(self, nums: List[int]) -> int: A = dict(zip(nums, [nums.count(i) for i in nums])) maxVal = max(A.values()) AReverse = dict(zip([nums.count(i) for i in nums],nums)) return AReverse[maxVal] # 자연스럽게 Time Limit Exceeded # collections library 를 가져와야겠다..
from collections import Counter class Solution: def majorityElement(self, nums: List[int]) -> int: A = Counter(nums) maxVal = max(A.values()) AReverse = dict(zip(A.values(),A.keys())) return AReverse[maxVal]
#memo
Couter() 함수 내부코드가 궁금해진다.. 속도차이가..
Runtime: 152 ms, faster than 98.22% of Python3 online submissions for Majority Element.
Memory Usage: 15.4 MB, less than 96.46% of Python3 online submissions for Majority Element.
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] [DP] 53. Maximum Subarray (0) 2021.10.05 [LeetCode]229. Majority Element II (0) 2021.09.29 [LeetCode]567. Permutation in String (0) 2021.09.26 [LeetCode]496. Next Greater Element I (0) 2021.09.26 [LeetCode] 1935. Maximum Number of Words You Can Type (0) 2021.09.25