본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 포켓몬 c++

by 오오오니 2023. 11. 7.

문제

숫자 배열이 주어졌을 때 ( 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을 이용한것이다.