티스토리 뷰

 public static int[] solution(int k, int[] score) {
    	int[] answer = new int[score.length];
    	
    	//PriorityQueue의 우선순위 컬렉션을 지정해주지 않으면, 오름차순으로 지정됨
    	PriorityQueue<Integer> priority = new PriorityQueue<>();
    	//(Collections.reverseOrder())라고 우선순위를 지정해주면 내림차순으로 지정됨
    	
    	for(int i = 0 ; i < score.length ; i++) {
    		//collection 객체 값을 추가할때 add 사용, offer는 queue
    		priority.add(score[i]);
    		
    		//객체를 저장하면 알아서 우선순위대로 재배치됨
    		System.out.println("priority.add(score[i]) >>> " + i +">>>>"  + priority.toString());
    		
    		if(priority.size() > k) {
    			//가장 작은 값을 반환하고 삭제함
    			System.out.println(" priority.poll() >> " + priority.poll());
    		}
    		//peek의 경우 큐의 가장 우선순위 (여기서는 내림차순이니까 가장 작은 숫자를 리턴함)
    		answer[i] = priority.peek();
    	}
    	
        System.out.println(Arrays.toString(answer));
        return answer;
    }
    public static void main(String[] args) {
    	int k = 4;
    	int[] score = {0, 300, 40, 300, 20, 70, 150, 50, 500, 1000};
    	solution(k, score);
	}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
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
글 보관함