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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

/*
문제 해설
k개는 귤을 소비하는 갯수로
tangerine 원소는 크기가 서로 다른 귤 종류에 대한 귤들을 나타낸 것이다.
귤 종류 중 최소 갯수를 가진 귤 종류를 제외한 나머지 귤 종류로 
k개만큼 고를 때 크기가 서로 다른 귤 종류를 리턴하면 된다.

1. map을 통해 귤 종류의 갯수를 카운팅 해 각각 셋팅한다. [종류] : [갯수]
2. 갯수를 기준으로 내림차순 정렬을 하는데, map의 경우 두번째 값을 정렬 하기 위해
vector를 사용해야 한다.
3. for문 사용해서 k개 만큼 내림차순으로 정렬 된 귤 종류의 갯수를 삭감하며 동시에 answer를 카운팅 한다.

*/
#include <string>
#include <vector>
#include<unordered_map>
#include<algorithm>
#include<iostream>
using namespace std;


bool cmp(const pair<int, int>& base, const pair<int, int>& tar){
    if(base.second==tar.second) return base.first<=tar.first;
    return base.second > tar.second;
}
int solution(int k, vector<int> tangerine) {
    int answer = 0;
    unordered_map<int, int> um;
    for(int idx = 0; idx < tangerine.size();++idx){ 
        um[tangerine[idx]]++;
    }
    vector<pair<int, int>> vec(um.begin(), um.end()); 
    sort(vec.begin(), vec.end(), cmp);

    for(const auto & v : vec){
        if(k>0){ 
            k-=v.second;
            answer++;
        }
        else break;
    }
    return answer;
}

 

 

 

map을 value 기준으로 정렬

https://velog.io/@keybomb/cpp-map%EC%9D%84-value-%EA%B8%B0%EC%A4%80%EC%9C%BC%EB%A1%9C-%EC%A0%95%EB%A0%AC%ED%95%98%EA%B8%B0

+ Recent posts