반응형
아래의 문제에 대하여 C++ 의 해쉬에 해당하는 unordered map 과 array 로 구현했을 때, 속도 비교를 하고자 합니다
최빈값 문제는 다음과 같습니다

Array 기반으로 해결하는 방법의 코드입니다
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> array) {
int array_list[1000] = {0,};
int max = 0;
int out = -1;
for (int i = 0; i < array.size(); i++) {
array_list[array[i]] += 1;
if (array_list[array[i]] > max) {
max = array_list[array[i]];
out = array[i];
} else if (array_list[array[i]] == max) {
out = -1;
}
}
return out;
}
Hash 기반으로 해결하는 다른 분의 코드입니다.
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
int solution(vector<int> array) {
int answer = 0;
int maxV = 0;
unordered_map<int,int> um;
for(const auto v : array)
{
um[v]++;
}
for(const auto& v : um)
{
if(v.second > maxV)
{
maxV = v.second;
answer = v.first;
}
else if(v.second == maxV)
{
answer = -1;
}
}
return answer;
}
실행결과: 특정 데이터에서 Hash 기반 구현이 Array 기반 구현보다 느린 것을 확인할 수 있습니다

반응형
'Development > 알고리즘' 카테고리의 다른 글
| [C++] 프로그래머스, 정수를 나선형으로 배치하기 (상태 정보를 이용) (0) | 2025.05.15 |
|---|---|
| [C++] 행렬 곱셈 일반화 코드 (백준 2740) (2) | 2022.11.30 |
| [Matlab] bubble sort (버블 정렬) (0) | 2022.09.22 |
| [Matlab] quicksort (퀵소트) (0) | 2022.09.22 |
| [C++] 백준 2609 최대공약수와 최소공배수 (유클리드 호제법 - O(logN)) (0) | 2022.02.08 |