Algorithm/Programmers

[10μ£Όμ°¨] ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ μ΄μ€‘μš°μ„ μˆœμœ„ν

do-oni 2021. 10. 2. 02:37

 

μ΄μ€‘μš°μ„ μˆœμœ„ν λ¬Έμ œν’€μ΄

πŸ’»Q

이쀑 μš°μ„ μˆœμœ„ νλŠ” λ‹€μŒ 연산을 ν•  수 μžˆλŠ” 자료ꡬ쑰λ₯Ό λ§ν•©λ‹ˆλ‹€.

이쀑 μš°μ„ μˆœμœ„ 큐가 ν•  μ—°μ‚° operationsκ°€ λ§€κ°œλ³€μˆ˜λ‘œ μ£Όμ–΄μ§ˆ λ•Œ, λͺ¨λ“  연산을 μ²˜λ¦¬ν•œ ν›„ 큐가 λΉ„μ–΄μžˆμœΌλ©΄ [0,0] λΉ„μ–΄μžˆμ§€ μ•ŠμœΌλ©΄
[μ΅œλŒ“κ°’, μ΅œμ†Ÿκ°’]을 return ν•˜λ„λ‘ solution ν•¨μˆ˜λ₯Ό κ΅¬ν˜„ν•΄μ£Όμ„Έμš”.
πŸ’‍♀️ μ œν•œ 사항
  • operationsλŠ” 길이가 1 이상 1,000,000 μ΄ν•˜μΈ λ¬Έμžμ—΄ λ°°μ—΄μž…λ‹ˆλ‹€.
  • operations의 μ›μ†ŒλŠ” 큐가 μˆ˜ν–‰ν•  연산을 λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
    • μ›μ†ŒλŠ” “λͺ…λ Ήμ–΄ 데이터” ν˜•μ‹μœΌλ‘œ μ£Όμ–΄μ§‘λ‹ˆλ‹€. - μ΅œλŒ“κ°’/μ΅œμ†Ÿκ°’μ„ μ‚­μ œν•˜λŠ” μ—°μ‚°μ—μ„œ μ΅œλŒ“κ°’/μ΅œμ†Ÿκ°’μ΄ λ‘˜ 이상인 경우, ν•˜λ‚˜λ§Œ μ‚­μ œν•©λ‹ˆλ‹€.
  • 빈 큐에 데이터λ₯Ό μ‚­μ œν•˜λΌλŠ” 연산이 μ£Όμ–΄μ§ˆ 경우, ν•΄λ‹Ή 연산은 λ¬΄μ‹œν•©λ‹ˆλ‹€.

μž…μΆœλ ₯ 예

μž…μΆœλ ₯ 예 μ„€λͺ…
16을 μ‚½μž… ν›„ μ΅œλŒ“κ°’μ„ μ‚­μ œν•©λ‹ˆλ‹€. λΉ„μ–΄μžˆμœΌλ―€λ‘œ [0,0]을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
7,5,-5λ₯Ό μ‚½μž… ν›„ μ΅œμ†Ÿκ°’μ„ μ‚­μ œν•©λ‹ˆλ‹€. μ΅œλŒ€κ°’ 7, μ΅œμ†Œκ°’ 5λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

 

πŸ’‘A

μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬ν•  μš°μ„ μˆœμœ„νμ™€ λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬ν•  μš°μ„ μˆœμœ„νλ₯Ό λ§Œλ“€κ³  String λ°°μ—΄κ°’ operationμ—μ„œ
substring을 μ‚¬μš©ν•΄ IμΌλ•Œ 값을 μ €μž₯ν•΄μ£Όκ³  D 1μΌλ•Œ μ΅œλŒ€κ°’ μ‚­μ œ, D -1μΌλ•Œ μ΅œμ†Œκ°’ μ‚­μ œ ν›„ answer λ°°μ—΄μ—μ„œ 각각 값을 뽑아 μ €μž₯ν•˜μ—¬ λ°˜ν™˜ν•΄ μ€€λ‹€.
import java.util.*;

public class Solution {

    public int[] solution(String[] operations) {
        int[] answer = new int[2];

        PriorityQueue<Integer> pq = new PriorityQueue<>();  //μ˜€λ¦„μ°¨μˆœ
        PriorityQueue<Integer> maxPq = new PriorityQueue<>(Collections.reverseOrder());  //λ‚΄λ¦Όμ°¨μˆœ
        
        for (String o : operations) {
            
            if (o.substring(0,1).equals("I")) {
                int value = Integer.valueOf(o.substring(2));     
                pq.offer(value);
                maxPq.offer(value);          
            }          
           
            else if (!pq.isEmpty()) {
                //μ΅œλŒ€κ°’ μ‚­μ œ
                if (o.equals("D 1")) {
                    int value = maxPq.poll();
                    pq.remove(value);
                }
                //μ΅œμ†Œκ°’ μ‚­μ œ
                else if (o.equals("D -1")) {
                    int value = pq.poll();
                    maxPq.remove(value);       
                }
            }            
        }

        if (!pq.isEmpty()) {
            answer[0] = maxPq.peek();
            answer[1] = pq.peek();
        }

        return answer;
	    }
	}​