본문 바로가기

problem solving

[프로그래머스]체육복

예외처리가 중요한 문제다.

정렬한 후에 잃어버린 번호와  여벌을 가진 번호가 중복된다면 서로 짝을 맞출 수 있도록 예외처리 한다면

쉽게 문제를 해결할 수 있다.

#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
 
using namespace std;
 
int solution(int n, vector<int> lost, vector<int> reserve) {
    int answer = n;
    int idx = 0;
    int count = 0;
    sort(lost.begin(), lost.end());
    sort(reserve.begin(), reserve.end());    
    for(int i = 0; i < lost.size(); i++) {
        while (idx < reserve.size() && lost[i] - reserve[idx] > 1) {
            idx++;
        }
        if(i < lost.size() - 1 && lost[i + 1== reserve[idx]) {
            i++;
        }
        if(idx >= 0 && lost[i] == reserve[idx + 1]) {
            idx++;
        }
        if(abs(reserve[idx] - lost[i]) <= 1) {
            count++;
            idx++;            
            if(idx == reserve.size()) { break; }
 
        }
        
    }
    answer += count - lost.size();
    return answer;
}
cs