Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 27 |
28 | 29 | 30 |
Tags
- 그리디
- 이중우선순위큐 자바
- 백준
- 프로그래머스 이중우선순위큐 java
- DBASE&
- 면접 필수 질문
- 위상정렬
- ansi sql 단점
- DP
- 디베이스앤
- 프로그래머스
- Gradle
- oracle ansi sql
- SQL
- 개발자 면접 준비
- DFS
- BFS
- 이분탐색
- 백트래킹
- 프로그래머스 이중우선순위큐 자바
- 이중우선순위큐 java
- oracle ansi
- 디베이스앤 인턴 후기
- CJ DBASE&
- Spring Boot
- JPA
- Java
- IT 면접 준비
- 프로그래머스 이중우선순위큐
- ansi sql 장점
Archives
- Today
- Total
쉬운 프로그래밍
[알고리즘] 프로그래머스 - 이중우선순위큐 - JAVA 본문
https://programmers.co.kr/learn/courses/30/lessons/42628
문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어수신 탑(높이)
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
입출력 예
operations | return |
["I 16","D 1"] | [0,0] |
["I 7","I 5","I -5","D -1"] | [7,5] |
입출력 예 설명
16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.
우선순위 큐 사용 소스코드
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> asc = new PriorityQueue<>();
PriorityQueue<Integer> desc = new PriorityQueue<>(Collections.reverseOrder());
int[] answer = {0, 0};
for (String s : operations) {
String[] arr = s.split(" ");
if (arr[0].equals("I")) {
asc.offer(Integer.parseInt(arr[1]));
desc.offer(Integer.parseInt(arr[1]));
}
else {
if (!asc.isEmpty()) {
if (arr[1].equals("1")) {
int max = desc.poll();
asc.remove(max);
}
else {
int min = asc.poll();
desc.remove(min);
}
}
}
}
if (asc.isEmpty()) {
return answer;
}
answer[0] = desc.peek();
answer[1] = asc.peek();
return answer;
}
}
remove를 사용하면 코드를 짧게 할 수 있다.
우선순위큐 사용X 소스코드
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
List<Integer> list = new ArrayList<>();
int[] answer = new int[2];
for (int i = 0; i < operations.length; i++) {
String[] s = operations[i].split(" ");
if (s[0].equals("I")) {
list.add(Integer.parseInt(s[1]));
Collections.sort(list);
}
else {
if (list.size() > 0) {
if (s[1].equals("1")) {
Collections.sort(list, Collections.reverseOrder());
list.remove(0);
}
else {
Collections.sort(list);
list.remove(0);
}
}
}
}
if (list.size() == 0) {
answer[0] = 0;
answer[1] = 0;
return answer;
}
Collections.sort(list, Collections.reverseOrder());
answer[0] = list.get(0);
answer[1] = list.get(list.size() - 1);
return answer;
}
}
Comments