본문 바로가기
Computer Science/알고리즘

leetcode 169) Majority Element

by eeeun:) 2022. 2. 21.
반응형

LV. Easy 😎

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 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

 

문제 해결법

과반수가 넘는 수가 무조건 있다고 문제에 명시되어 있으니, nums를 정렬한 후 중간 인덱스의 값을 리턴하면 정답!

 

해결 코드
class Solution {
public:
	int majorityElement(vector<int>& nums) {
		sort(nums.begin(), nums.end());
		return nums[nums.size() / 2];
	}
};

728x90

댓글