본문 바로가기

개발 관련 기타/알고리즘

[프로그래머스] (C++) 체육복

문제는 이 링크를 타고 가면 있습니다.

 

이 문제는 정렬을 필요로 합니다. 왜일까요?

 

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

using namespace std;

int solution(int n, vector<int> lost, vector<int> reserve) {
  int answer = 0;
  sort(lost.begin(), lost.end());
  sort(reserve.begin(), reserve.end());
  vector<int>::iterator lost_iter, res_iter;
  lost_iter = lost.begin();
  res_iter = reserve.begin();
  while ((lost_iter != lost.end()) && (res_iter != reserve.end())) {
    if (*lost_iter < *res_iter) {
      lost_iter++;
    } else {
      if (*lost_iter == *res_iter) {
        lost.erase(lost_iter);
        reserve.erase(res_iter);
      } else res_iter++;
    }
  }
  lost_iter = lost.begin();
  res_iter = reserve.begin();
  while ((lost_iter != lost.end()) && (res_iter != reserve.end())) {
    if (*lost_iter + 1 <  *res_iter) {
      lost_iter++;
    } else {
      if ((*lost_iter - 1 == *res_iter) || (*lost_iter + 1 == *res_iter)) {
        lost.erase(lost_iter);
        reserve.erase(res_iter);
      } else res_iter++;
    }
  }
  return n - lost.size();
}