프로그래머스 이중우선큐

아래처럼하면 될듯하다.

위 방법대로 하려다 잘 안된다. max 큐에서 min큐로 변경될 때 연산이 하나씩 틀어진다. 결국 max queue를 poll하면 min queue를 클리어하고, max queue로 업데이트 했다.


import java.util.Collections;
import java.util.regex.*;
import java.util.PriorityQueue;

public class Main {

	public static void main(String[] args) {
		// 시작..
		//		String[] operations = { "I16", "I10", "I20", "D1" };
		String[] operations = { "I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333" };

		Solution sol = new Solution();
		int[] t = sol.solution(operations);
		System.out.println(t[0]+","+ t[1]);
	}// void main

}

class Solution {
	public int[] solution(String[] operations) {
		Pattern tmpNumber = Pattern.compile("(-[0-9]{1,}|[0-9]{1,})");
		PriorityQueue<Work> pqMax = new PriorityQueue<>();
		PriorityQueue<Work> pqMin = new PriorityQueue<>(Collections.reverseOrder());


		for (int in = 0; in < operations.length; in++) {
			//			System.out.println("인자: " + operations[in] + operations[in]);
			String op = operations[in].substring(0, 1);
			//정규표현식으로 숫자만 출력.
			Matcher tmpMatcher = tmpNumber.matcher(operations[in]);
			String tmpNum = "";
			Integer num = 0;
			//			int num = Integer.parseInt(tmpMatcher.group());
			while (tmpMatcher.find()) {
				tmpNum = tmpMatcher.group();
				//				System.out.println(tmpMatcher.group());
			}
			num = Integer.parseInt(tmpNum);
			//			System.out.println(num);
			//			System.out.println(tmpMatcher.find());

			//			int num = Integer.parseInt(operations[in + 1]);
			if (op.equals("I")) {

				pqMax.add(new Work(num));
				pqMin.add(new Work(num));

			} else if (op.equals("D"))
				if (num.equals(1)) {
					pqMax.poll();
					if (pqMax.size() == 0)
						//size가 0이면 마지막 1개를 취출했음.
						pqMin.poll();
					else {
						pqMin.clear();
						pqMin.addAll(pqMax);
					}
				} else if (num.equals(-1)) {
					pqMin.poll();
					if (pqMin.size() == 0)
						//size가 0이면 마지막 1개를 취출했음.
						pqMax.poll();
					else {
						pqMax.clear();
						pqMax.addAll(pqMin);
					}

				}

		}

		/*
		 * System.out.println("Max 큐"); while (!pqMax.isEmpty()) {
		 * System.out.println(pqMax.poll().number); }
		 * 
		 * System.out.println("Min 큐"); while (!pqMin.isEmpty()) {
		 * System.out.println(pqMin.poll().number); }
		 */

		int[] answer = new int[2];
		if (pqMax.size() != 0)
			answer[0] = pqMax.poll().number;
		else
			answer[0] = 0;
		if (pqMin.size() != 0)
			answer[1] = pqMin.poll().number;
		else
			answer[1] = 0;

		return answer;
	} //solution

}

class Work implements Comparable<Work> {
	int number;

	Work(Integer num) {
		this.number = num;
	}

	@Override
	public int compareTo(Work arg0) {
		// TODO Auto-generated method stub

		return this.number > arg0.number ? -1 : 1;
	}

}

댓글 남기기

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.