‡ CODING TEST STUDY ‡/º 프로그래머스
[프로그래머스 | Java Lv.3] 이중우선순위큐
Trudy | 송연
2024. 5. 15. 01:58
문제
https://school.programmers.co.kr/learn/courses/30/lessons/42628
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
메모
j를 출력했을 때 I가 잘 나오는데 큐에 삽입이 되고 있지 않은 걸 확인했다.
if( j == "I" ) 를 해서 그랬던 것
for(String s : operations){
System.out.println("des = " + des);
String j = s.split(" ")[0];
System.out.println("j = " + j);
Integer v = Integer.parseInt(s.split(" ")[1]);
System.out.println("v = " + v);
if(j == "I") {
System.out.println("여기 들어옴");
des.offer(v);
asc.offer(v);
}
문자 vs. 문자열
자바에서는 문자(character)와 문자열(string)이 명확히 구분된다.
문자는 작은따옴표(')로 표시되며, 문자열은 큰따옴표(")로 표시됨
예를 들어, 'I'와 "I"는 전혀 다른 타입!
'I'는 char 타입이고, "I"는 String 타입이다. 따라서 j가 char 타입의 'I'일 경우, if (j == "I")는 타입 불일치로 인해 false를 반환한다.
문자(char)일 때
만약 j가 문자(char) 타입이라면, 비교 구문을 문자로 변경해야 합니다
if (j == 'I') {
// 조건이 참일 때 실행할 코드
}
문자열(String)일 때
만약 j가 문자열(String) 타입이고 "I"와 비교하려면, 현재의 구문(if (j == "I"))이 적절.
하지만 자바에서 문자열 비교는 equals() 메소드를 사용하는 것이 더 안전하다
if ("I".equals(j)) {
// 조건이 참일 때 실행할 코드
}
최종 코드
package week2.baek.heap;
import org.w3c.dom.ls.LSOutput;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Ex3 {
public int[] solution(String[] operations) {
int[] answer = new int[2];
PriorityQueue<Integer> des = new PriorityQueue(Collections.reverseOrder());
PriorityQueue<Integer> asc = new PriorityQueue();
for(String s : operations){
String j = s.split(" ")[0];
Integer v = Integer.parseInt(s.split(" ")[1]);
if(j.equals("I")) {
des.offer(v);
asc.offer(v);
}
//D 일 때 - 삭제 연산
else {
//안해주면 null 포인터 에러 뜸
if(des.isEmpty()) continue;
//최솟값 삭제
else if(v < 0) {
int min = asc.poll();
des.remove(min);
}
//최댓값 삭제
else{
int max = des.poll();
asc.remove(max);
}
}
}
if(des.isEmpty())
return new int[] {0, 0};
if(des.size() > 0) {
answer[0] = des.poll();
answer[1] = asc.poll();
}
return answer;
}
}
class Ex3Main {
public static void main(String[] args) {
Ex3 ex3 = new Ex3();
String[] operations = {"I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"};
System.out.println(ex3.solution(operations));
}
}