Algorithm/Programmers

[Programmers] Lv.0 / 전국 대회 선발 고사 / Java

unknownomad 2024. 2. 28. 07:40

문제

 

풀이

import java.util.Arrays;

class Solution {
    public int solution(int[] rank, boolean[] attendance) {
        int answer = 0;
        int[] sort = new int[rank.length];
        
        for(int i = 0; i < rank.length; i++) {
            if(attendance[i]) {
                sort[i] = rank[i];
            } else {
                rank[i] = Integer.MAX_VALUE;
            }
        }
        Arrays.sort(rank);
        
        for(int i = 0; i < sort.length; i++) {
            if(rank[0] == sort[i]) {
                answer += i * 10000;
            } else if(rank[1] == sort[i]) {
                answer += i * 100;
            } else if(rank[2] == sort[i]) {
                answer += i;
            }
        }
        return answer;
    }
}
import java.util.Comparator;
import java.util.stream.IntStream;

class Solution {
    public int solution(int[] rank, boolean[] attendance) {
        return IntStream.range(0, rank.length) // 0 ~ rank.length 까지의 idx 생성 stream
                .filter(i -> attendance[i]) // 위 idx 중, attendance 요소가 true 인 idx only
                .boxed() // convert IntStream to Stream<Integer>
                .sorted(Comparator.comparing(i -> rank[i])) // rank[i] 기준 정렬, 오름차순
                .limit(3)
                .reduce((current, next) -> current * 100 + next) // reduce() 누적 계산, 각 요소마다 current * 100 + next 수행
                .get(); // Optional 객체에서 실제 값 가져옴
    }
}
import java.util.PriorityQueue;

class Solution {
    public int solution(int[] rank, boolean[] attendance) {
        /**
        * (a, b) -> rank[a] - rank[b] 두 학생 비교한 idx 결과 반환
        * 등수가 높은 것(1등)부터 작은 것(100등) 순으로 idx 정렬
        * 등수가 높을수록 우선순위 높아짐
        * 결과가 음수면 a > b
        * 결과가 양수면 a < b
        * 결과가 0 이면 a == b
        */
        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