[프로그래머스/C++] 귤 고르기

Zero·2023년 3월 30일
0

프로그래머스 Lv2

목록 보기
1/1

문제링크

귤 고르기

설명

  1. sort를 이용해 tangerine 정렬
  2. 반복문 for에서 i값과 i+1값이 같으면 same + 1
  3. ii+1이 다를때 count(same+1)값 추가 //같은 크기에 귤 개수를 배열화!
  4. count 배열 내림차순으로 정리 (greater<>() 이용)
  5. 큰 값부터 차례대로 k에서 빼기 (while (k > 0)) -> erase로 뺀 값 지우기

코드

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

using namespace std;

int solution(int k, vector<int> tangerine) {
    int answer = 0;
    
    vector<int> count;
    int same = 0;
    
    sort(tangerine.begin(), tangerine.end());
    
    for (int i=0; i<tangerine.size(); i++)
    {
        if (tangerine[i] == tangerine[i+1])
        {
            same++;
        }else
        {
            count.push_back(same+1);
            same = 0;
        }
    }
    
    sort(count.begin(), count.end(), greater<>());
    
    while (k>0)
    {
        k-=count.front();
        answer++;
        count.erase(count.begin());
    }
    
    return answer;
}
profile
Algorithm

0개의 댓글