반응형
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
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 133) Clone Graph (0) | 2022.02.23 |
---|---|
leetcode 171) Excel Sheet Column Number (0) | 2022.02.22 |
leetcode 1288) Remove Covered Intervals (0) | 2022.02.20 |
leetcode 1675) Minimize Deviation in Array (0) | 2022.02.19 |
leetcode 402) Remove K Digits (0) | 2022.02.18 |
댓글