
Top Interview 150
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.length1 <= n <= 5 * 104-109 <= nums[i] <= 109Follow-up: Could you solve the problem in linear time and in
O(1) space?
class Solution(object):
def majorityElement(self, nums):
return sorted(nums)[len(nums)//2]
Time: 4 ms (81.43%), Space: 13.4 MB (98.7%)
n/2번 이상 등장하는 최대 빈도의 수를 반환하는 문제이다.
나는 nums를 정렬해서 중간 인덱스에 위치하는 값을 반환해주었다. 왜냐하면, 최대 빈도수는 nums에서 절반 이상을 차지한다고 했으므로 nums의 중간 위치에 최대 빈도수가 위치할 수 밖에 없기 때문이다.
sorted() : len(nums // 2) : sorted_list[index] (indexing) :