Algorithm/C++ - 프로그래머스

프로그래머스 Level2 - 더 맵게 C++

ㅇㅇ잉 2021. 3. 26. 02:03

처음에는 vector를 sort시켜서 해볼까 싶었지만, 우선순위 큐로 푸는게 더 낫다.

우선순위 큐를 greater<int>로 선언해 작은 수가 top에 올 수 있도록 해준다.

 

1. 처음에 풀었던 코드

-1를 걸러주기 위해서 check를 사용했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <string>
#include <vector>
#include <queue>
using namespace std;
 
int solution(vector<int> scoville, int K) {
    int answer = 0;
    bool check = false;
    
    priority_queue<int,vector<int>,greater<int>> pq;
    for(int i=0;i<scoville.size();i++) pq.push(scoville[i]);
        
    while(pq.size()>=2){
        if(pq.top()<K){
            int s_first = pq.top(); pq.pop();
            int s_second = pq.top(); pq.pop();
            
            int sum = s_first+(s_second*2);
            pq.push(sum);
            answer++;
        }
        if(pq.top()>=K) return answer;
    }
    
    return -1;
}
cs

 

 

2. 다른 풀이 보고 수정한 코드

어우 깔끔하다

check같은 변수도 안 썼다.

역시 문제 풀고 나서 다른 분들 코드도 비교도해보고 리뷰도 해야 좀 실력이 느는 것 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <vector>
#include <queue>
using namespace std;
 
int solution(vector<int> scoville, int K) {
    int answer = 0;
  
    
    priority_queue<int,vector<int>,greater<int>> pq;
    for(int i=0;i<scoville.size();i++) pq.push(scoville[i]);
        
    while(pq.top()<K){
        if(pq.size()==1return -1;
        int s_first = pq.top(); pq.pop();
        pq.push(s_first+(pq.top()*2));
        pq.pop();
        answer++;
    }
    return answer;
}
cs