📄 문제
최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
📝 풀이
#include <string>
#include <vector>
#include <map>
#include <cmath>
using namespace std;
int solution(vector<int> array) {
map<int, int> m;
for(int n : array)
++m[n];
int maxValue = -1;
int res = -1;
for(const pair<int, int> p : m)
{
if(maxValue <= p.second)
{
if(maxValue == p.second)
return -1;
maxValue = p.second;
res = p.first;
}
}
return res;
}
- map을 이용하여 문제를 해결합니다.
- map의 second는 해당 n의 빈도를 나타냅니다.
- 가장 최빈값을 구한 후 최빈값이 중복되는지 확인하여 리턴합니다.
'algorithms (C++)' 카테고리의 다른 글
[C++][프로그래머스] 공원 산책 (1) | 2023.10.23 |
---|---|
[C++][프로그래머스] 달리기 경주 🔥 (1) | 2023.10.22 |
[C++][프로그래머스] 안전지대 (1) | 2023.10.22 |
[C++][프로그래머스] 한 번만 등장한 문자 (0) | 2023.10.22 |
[C++][프로그래머스] OX퀴즈 (1) | 2023.10.22 |