https://school.programmers.co.kr/learn/courses/30/lessons/42626
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
나의 답
import java.util.*;
class Solution {
public int solution(int[] scoville, int K) {
int answer = 0;
PriorityQueue<Integer> p = new PriorityQueue<>();
for(int s : scoville) p.add(s);
int count = 0;
while(p.peek()<K){
if(p.size()==1){
return count = -1;
}
int a = p.poll();
int b = p.poll();
int c = a+(b*2);
p.add(c);
count++;
}
answer = count;
return answer;
}
}
이번에 heap의 구조를 알아봤다.
자바로는 priorityQueue를 사용
- priorityQueue 선언 (우선순위가 낮은 숫자 순)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
- priorityQueue 선언 (우선순위가 높은 숫자 순)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
하면서 엄청 신기했다.
p.poll(), p.add()시에 가장 작은 값을 호출 가능하고, 호출 한 순간 정렬이 된다.
가장 낮은 수는 최 상단에 위치하게된다.
출처 : https://coding-factory.tistory.com/603
[Java] PriorityQueue(우선순위 큐) 클래스 사용법 & 예제 총정리
우선순위 큐(Priority Queue)란? 일반적으로 큐는 데이터를 일시적으로 쌓아두기 위한 자료구조로 스택과는 다르게 FIFO(First In First Out)의 구조 즉 먼저 들어온 데이터가 먼저 나가는 구조를 가집니다
coding-factory.tistory.com
'알고리즘' 카테고리의 다른 글
알고리즘 - 프로그래머스(숫자 문자열과 영단어) (0) | 2022.08.11 |
---|---|
알고리즘 - 프로그래머스(신규아이디 추천) (0) | 2022.08.09 |
알고리즘 - 프로그래머스(폰켓몬) (0) | 2022.07.12 |
알고리즘 - 프로그래머스 - 모의고사 (0) | 2022.07.09 |
알고리즘 - 프로그래머스 K번째수 (0) | 2022.07.08 |