코딩테스트/Programmers

[프로그래머스] 전국 대회 선발 고사

grove1212 2025. 1. 23. 10:56

스트림을 공부하면서 써먹어보려고 미숙하게나마 문제 푸는데 적용해보았다.

import java.util.stream.*;

class Solution {
    public int solution(int[] rank, boolean[] attendance) {
        int answer = 0;
        int []arr = IntStream.range(0, rank.length)
            .filter(i -> attendance[i]) //visited가 true인 경우만 필터링
            .map(i -> rank[i]) // 해당 인덱스의 rank값 추출
            .boxed() // IntStream을 IntegerStream으로 변환
            .sorted((a, b) -> a - b) // 내림차순 정렬
            .limit(3)
            .mapToInt(Integer::intValue)
            .toArray(); // int[]로 변환
        
        for(int i = 0; i<3; i++){
            for(int j = 0; j<rank.length; j++){
                if(arr[i] == rank[j]){
                    arr[i] = j;
                    break;
                }
            }
        }

        answer = 10000*arr[0] + 100*arr[1] + arr[2];
        
        return answer;
    }
}

코드 분석은 아래에

https://developerbbojak.tistory.com/entry/%EC%9E%90%EB%B0%94-%EC%8A%A4%ED%8A%B8%EB%A6%BC-%EC%98%88%EC%A0%9C-3

 

자바 스트림 예제 3

boxed() : IntStream을 IntegerStream으로 변환sorted() : IntStream에서는 수행되지 않고, 객체 스트림인 IntegerStream에서만 가능하다.toArray() : IntStream -> int[] 변환import java.util.stream.*;class Solution { public int solution(

developerbbojak.tistory.com

 

- PriorityQueue를 이용한 풀이

import java.util.PriorityQueue;

class Solution {
    public int solution(int[] rank, boolean[] attendance) {

        PriorityQueue<Integer> que = new PriorityQueue<>((a, b) -> rank[a] - rank[b]);
        for (int i = 0; i < attendance.length; i++) {
            if (attendance[i])
                que.add(i);
        }

        return que.poll() * 10000 + que.poll() * 100 + que.poll();
    }
}

 

https://school.programmers.co.kr/learn/courses/30/lessons/181851