728x90

https://school.programmers.co.kr/learn/courses/30/lessons/131127

 

프로그래머스

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

programmers.co.kr

10일동안 원하는 제품을 모두 할인해서 구매해야한다.

unoredred_map의 사용법이 신기했던 문제다.

#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include <deque>
using namespace std;

int solution(vector<string> want, vector<int> number, vector<string> discount) {
    int answer = 0;
    
    deque<string> dq;
    unordered_map<string, int> m;
    unordered_map<string, int> origin;    
     
    for(int i=0; i<want.size(); i++) {
        origin.insert({want[i], number[i]});
    }
    
    for(int i=0; i<10; i++) {
        string temp = discount[i];
        dq.push_back(temp);
        m[temp]++;
    }
        
    if(m == origin) {
        answer++;
    }

    for(int i=10; i<discount.size(); i++) {
        m[dq.front()]--;
        dq.pop_front();
        m[discount[i]]++;
        dq.push_back(discount[i]);
        
        bool check = true;
        for(int j=0; j<want.size(); j++) {
            
            if(m[want[j]] < origin[want[j]]) {
                check = false;
                break;
            }
        }
        if(check) {
            answer++;
        }
    }
        
    return answer;
}

맵에 있는 값을 --처리하여 0이 되어도, map에서 사라지지 않는다.

그렇기 때문에 비교하는 for문이 하나 더 들어가게 된다.

erase를 써서 지워버린다면, for문이 사라지고 == 처리로 비교가 한번에 가능해진다.

하지만 내가 사고 싶은 물건보다 더 많이 할인하는 경우를 체크하지 못하지 않을까 싶지만 사실 상관없다.
=>  애매한 부분이라 정확한 설명은 못하지만, ==처리로 같은지 확인할 수있다는 점을 알게 되었다는 점에서 신기하다.

#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include <deque>
using namespace std;

int solution(vector<string> want, vector<int> number, vector<string> discount) {
    int answer = 0;
    
    deque<string> dq;
    unordered_map<string, int> m;
    unordered_map<string, int> origin;    
     
    for(int i=0; i<want.size(); i++) {
        origin.insert({want[i], number[i]});
    }
    
    for(int i=0; i<10; i++) {
        string temp = discount[i];
        dq.push_back(temp);
        m[temp]++;
    }
        
    if(m == origin) {
        answer++;
    }

    for(int i=10; i<discount.size(); i++) {
        m[dq.front()]--;
        if(m[dq.front()] == 0) {
            m.erase(dq.front());
        }
        dq.pop_front();
        m[discount[i]]++;
        dq.push_back(discount[i]);
        
        if(m == origin) {
            answer++;
        }
    }
        
    return answer;
}
반응형

+ Recent posts