이 튜토리얼에서는 처음 발생한 후 최소 K 번 나타나는 배열의 요소 수를 찾는 프로그램에 대해 설명합니다.
이를 위해 정수 배열과 값 k가 제공됩니다. 우리의 임무는 고려한 요소 다음의 요소들 중에서 k번 발생하는 모든 요소를 세는 것입니다.
예시
#include <iostream>
#include <map>
using namespace std;
//returning the count of elements
int calc_count(int n, int arr[], int k){
int cnt, ans = 0;
//avoiding duplicates
map<int, bool> hash;
for (int i = 0; i < n; i++) {
cnt = 0;
if (hash[arr[i]] == true)
continue;
hash[arr[i]] = true;
for (int j = i + 1; j < n; j++) {
if (arr[j] == arr[i])
cnt++;
//if k elements are present
if (cnt >= k)
break;
}
if (cnt >= k)
ans++;
}
return ans;
}
int main(){
int arr[] = { 1, 2, 1, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 1;
cout << calc_count(n, arr, k);
return 0;
} 출력
1