문제
숫자 배열이 주어졌을 때 ( ex) [3,3,2,3,2,2] )
중복되지 않는 숫자의 개수를 구한다. 숫자 배열의 절반 길이를 초과하면 절반 길이를 출력한다.
풀이
배열의 인덱스를 이용해서 숫자가 나왔는지 체크했다. 절반보다 많이 나오면 숫자의 개수를 구하는 것을 멈췄다.
#include <vector>
#include <iostream>
using namespace std;
bool n[200001];
int solution(vector<int> nums)
{
int answer = 0;
int select_number=0;
int pick_size = nums.size()/2;
int nums_size = nums.size();
int max_index=0;
for(int i=0; i<nums_size ;i++){
n[nums[i]]=true;
if(nums[i]>max_index)
max_index=nums[i];
}
for(int i=1;i<=max_index ; i++){
if(n[i])
select_number++;
if(select_number==pick_size)
break;
}
answer=select_number;
return answer;
}
다른 사람의 풀이
unordered_set, min을 이용해서 풀었다.
키의 존재유무만 궁금하기 때문에 unordered_map보다는 set을 이용한것이다.
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 숫자 문자열과 영단어 c++ (0) | 2023.11.23 |
---|---|
[프로그래머스] 하노이의 탑 c++ (0) | 2023.11.11 |
[프로그래머스] 정수삼각형 c++ (0) | 2023.11.06 |
[프로그래머스] 타겟넘버 c++ (0) | 2023.09.28 |
[프로그래머스] 교점에 별 만들기 c++ (0) | 2023.09.26 |