[C_C++]코딩테스트 연습/[프로그래머스] level 1
[C++] 프로그래머스 - 폰켓몬 (set)
코딩굼벵이
2021. 6. 29. 20:48
728x90
내 풀이 )
set을 쓰긴 했는데 set 사용법과 algorithm 헤더에 min까지 들어있는지 잘 몰라서 코드가 길어졌다.
#include <vector>
#include <set>
#include <iostream>
using namespace std;
int solution(vector<int> nums)
{
int answer = 0;
int nums_length = nums.size();
set<int> kind;
for (int i = 0; i < nums_length; i++) {
kind.insert(nums[i]);
}
answer = nums_length/2 > kind.size() ? kind.size() : nums_length/2;
return answer;
}
다른 사람 풀이 참고)
1. set 선언할 때 vector의 반복자 멤버함수인 begin, end를 이용해 복사 및 중복 제거가 가능했다.
2. algorithm 헤더에 min 함수가 있어 작은 것을 선택할 수 있다.
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
int solution(vector<int> nums)
{
set<int> s(nums.begin(), nums.end());
return min(nums.size() / 2, s.size());
}