알고리즘/PROGRAMMERS

프로세스(Lv.2)

현대타운301 2024. 3. 22. 16:51

     


     

    문제 설명

     

     

     

    입출력 예시

     

     

    요약

    location에 해당하는 index의 prioties 요소가 몇 번째로 출력되는지 구하기

     


     

    풀이

     

    접근 방식

    1. priority와 location을 갖는 객체 생성

      → Priority class 객체 생성

     

    2. Queue 형태로 객체 조회

      → ArrayList로 큐 구현


     

    코드리뷰

     

    import java.util.*;
    
    class Priority {	// priority와 location을 담을 객체 클래스
        int priority;
        int location;
        public Priority(int priority, int location) {
            this.priority = priority;
            this.location = location;
        }
    }
    
    class Solution {
        public int solution(int[] priorities, int location) {
            int answer = 0;
            List<Priority> list = new ArrayList<>();
            for(int i = 0; i < priorities.length; i++) {
                Priority obj = new Priority(priorities[i], i);
                list.add(obj);
            }
            int count = 0;	// 프로세스 진행 count
            while(!list.isEmpty()) {
                Priority objOut = list.remove(0);	// FIFO 형식으로 조회
                if(list.stream().anyMatch(others -> others.priority > objOut.priority)) {
                    list.add(objOut);	// list안에 priority가 큰 객체가 있다면 다시 add
                } else {
                    count++;	// 해당 프로세스 진행을 의미
                    if(objOut.location == location) {
                        answer = count;	// 해당 위치의 프로세스가 찾던 프로세스라면
                        break;	// while문 종료
                    }
                }
            }
            return answer;
        }
    }