체육복

현빈벨로그·2022년 1월 30일

프로그래머스

목록 보기
4/4

💪체육복 (프로그래머스)

사용언어 : C++
여러가지 예외상황만 잘 생각해주면 간단한 문제


1. 정답풀이

  • 학생 배열의 처음과 끝만 고려해주면 된다
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int solution(int n, vector<int> lost, vector<int> reserve) {
    vector<int> list(n, 1);
    int answer=0;
    for (int i = 0; i < lost.size(); i++) {
        list[lost[i] - 1]--;
    }
    for (int i = 0; i < reserve.size(); i++) {
        list[reserve[i] - 1]++;
    }
    for (int i = 0; i < list.size(); i++) {
        if (list[i] == 0) {
            if (i != 0 && list[i - 1] == 2) {
                list[i - 1]--;
                list[i]++;
            }
            else if (i != list.size() - 1 && list[i + 1] == 2) {
                list[i + 1]--;
                list[i]++;
            }
        }
    }
    for (int i = 0; i < list.size(); i++) {
        if (list[i] !=0) {
            answer++;
        }
    }
    return answer;
}

2. 첫 풀이(75점)

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int solution(int n, vector<int> lost, vector<int> reserve) {
    int answer = 0;
    int clothes[32];
    fill_n(clothes,32,1);
    
    for(int i=0; i<lost.size(); i++){
    	clothes[lost[i]] = 0;
    }
    for(int i=0; i<reserve.size(); i++){
    	clothes[reserve[i]] = 2;
    }
    
     for(int l : lost){
        for(int r : reserve){
            if (l == r){
                clothes[l] = 1;
            }
        }
    }
    
    for(int i=1; i<n+1; i++){
        if (clothes[i] > 1 && clothes[i+1] == 0){
            clothes[i]--;
            clothes[i+1]++;
        }else if (clothes[i] > 1 && clothes[i-1] == 0){
            clothes[i]--;
            clothes[i-1]++;
        }
    }
    
    for(int i=1; i<n+1; i++){
        if(clothes[i] > 0){
            answer++;
        }
    }

     
    return answer;
}

3. 링크

https://programmers.co.kr/learn/courses/30/lessons/42862

0개의 댓글