프로그래머스/2레벨

롤케이크 자르기/C++

Koalitsiya 2023. 2. 15. 14:55
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이 방법

map 자료구조를 이용하여 일단 m2에 topping의 데이터를 전부 담는다. 이후 m1[topping]에 더하고 m2[topping]에서 빼는 것을 반복하며 m1, m2의 크기를 비교해 크기가 같다면 롤케이크가 공평하게 잘린것이므로 answer++해준다.

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

using namespace std;

int solution(vector<int> topping) {
    int answer = 0;
    
    map<int, int> m1;
    map<int, int> m2;
    
    for(int i = 0; i < topping.size(); i++)
        m2[topping[i]]++;
    
    for(int i = 0; i < topping.size(); i++) {
        m1[topping[i]]++;
        m2[topping[i]]--;
        
        if(!m2[topping[i]]) m2.erase(topping[i]);
        if(m1.size() == m2.size()) answer++;
    }
    
    return answer;
}