취미가 좋다

169. Majority Element 본문

알고리즘 문제풀이/Leetcode

169. Majority Element

benlee73 2021. 8. 12. 21:03

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

 

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

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

 

Solution

class Solution:
    def majorityElement(self, nums):
        nums.sort()
        return nums[len(nums) // 2]
  • 정렬하고 나면 리스트의 중앙에는 무조건 과반수에 해당하는 수가 있다.
  • 이걸 떠올리기가 쉽지 않다.

'알고리즘 문제풀이 > Leetcode' 카테고리의 다른 글

198. House Robber  (0) 2021.08.16
189. Rotate Array  (0) 2021.08.13
155. Min Stack  (0) 2021.08.06
146. LRU Cache  (0) 2021.08.05
136. Single Number  (0) 2021.08.04
Comments