vector 활용하기

Subin·2024년 10월 11일

Algorithm

목록 보기
46/69

최근 푼 문제들에서, vector를 잘 활용하는 문제들이 있어서 정리를 해보고자 한다.

보통 map을 사용해서 value값에 bool형태를 넣었는데, int를 사용해서 특정 key값을 가진 사람 수를 분류해두고자 할 때
vec[i]++;
혹은
map[i]++;
를 활용하는 경우가 많았다.

예시1

#include <string>
#include <vector>
#include <map>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    map<string, int> mPart;
    // participant 명단을 하나씩 돌면서 completion에 있으면 map<string, int>에 사람 수 증가 (동명이인이면 2이상 됨)
    // map의 1이상인 값을 answer에 return
    for(auto p: participant)
    {
        mPart[p]++;
    }
    for(auto c: completion)
    {
        mPart[c]--;
    }
    for(auto it=mPart.begin(); it != mPart.end(); it++)
    {
        if((*it).second > 0)
            answer = (*it).first;
    }
    
    return answer;
}


예시2

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(string X, string Y) {
    string answer = "";
    vector<int> countX(10,0), countY(10,0);
    // 공통으로 나타나는 정수를 큰 수부터 정렬해서 return
    // 공통으로 나타나는 정수 없으면 -1 return
    for(char x: X)
    {
        countX[x-'0']++;
    }
    for(char y: Y)
    {
        countY[y-'0']++;
    }
    // 공통으로 나타나는 정수 찾기(countX, countY 중에 min값만큼 answer에 해당 수 넣기)
    for(int i=0; i<countX.size(); i++)
    {
        for(int j=0; j<min(countX[i], countY[i]); j++)
        {
            answer += i + '0'; // char형태로 string에 추가
        }
    }
    
    // 큰 수부터 정렬
    if(answer != "")
        sort(answer.begin(), answer.end(), greater<>());
    else // 비어있으면 -1 return
        answer = "-1";
    while(1)
    {
        if(answer[0] == '0' && answer.length() > 1)
            answer.erase(answer.begin());
        else
            return answer;
    }
}

여기서, char값을 int로 변환하고자 할 때 char - '0' 을 하고
반대로 int값을 char형으로 변환하고자 할 때 int + '0'을 한다는 점 알아두기

profile
성장하며 꿈꾸는 삶을 살아가고 있는 대학생입니다😊

0개의 댓글