프로세스 (자바)

김재현·2023년 12월 27일
0

알고리즘 풀이

목록 보기
67/89

문제

정답 코드

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        
        // map에 (key:위치, value:우선순위)으로 넣어놓음 (while 조건 비교를 위해)
        Map<Integer,Integer> map = new HashMap<>();
        for (int i=0;i< priorities.length;i++) {
            map.put(i,priorities[i]);
        }

        int orderIndex = 0; // 몇번째 값을 검증할건지
        while (map.get(location)!=0) {
            int doIndex=0; // 실행할지말지
            for (int i=0;i< priorities.length;i++) {
                doIndex++;
                if (priorities[orderIndex]<priorities[i]) {  // 더 높은 우선순위가 있다면 doindex를 0으로
                    doIndex=0;
                    break;
                }
            }
            if (doIndex == priorities.length) {  // 더 높은 우선순위가 없었다면 실행
                answer++;
                map.put(orderIndex,0);  // while에서 비교를 위해 0으로 만듦
                priorities[orderIndex]=0;  // 우선순위를 0으로 만들어버림
            }
            orderIndex++;
            if (orderIndex == priorities.length) {  // 한바퀴 다 돌았으면 다시 처음으로
                orderIndex=0;
            }
        }
        
        return answer;
    }
}

Queue를 연습해봐야하는 문제인걸 알기 때문에 처음에 Queue로 시도했으나 막혀서 잘 안됐다.
그래서 내게 익숙한 map과 index를 이용한 while, for문으로 풀이했다.

풀고나서 보니 어쨌든 속도도 괜찮고 풀었으면 그만 아닌가 싶기도 하다.

다른 사람 풀이

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        int l = location;

        Queue<Integer> que = new LinkedList<Integer>();
        for(int i : priorities){
            que.add(i);
        }

        Arrays.sort(priorities);
        int size = priorities.length-1;



        while(!que.isEmpty()){
            Integer i = que.poll();
            if(i == priorities[size - answer]){
                answer++;
                l--;
                if(l <0)
                    break;
            }else{
                que.add(i);
                l--;
                if(l<0)
                    l=que.size()-1;
            }
        }

        return answer;
    }
}

이분이야말고 Queue를 이용하여 문제를 풀이했다.

우선 Queue로 que를 선언한뒤 priorities의 값을 순서대로 모두 담아줬다.

그 뒤에 priorities 배열을 오름차순으로 정렬했다!!

이렇게하면 나처럼 index를 주지 않아도 현재 poll 해서 나온 값이 최대값인지 확인 할 수 있는 것이다.

for문을 돌리지 않아도 되기 때문에 훨씬 효율적인 풀이라고 할 수 있겠다.
priorities를 정렬한다는 생각을 못했다!

그리고 여기서 location으로 index를 만들어서 while문이 언제 끝날지 확인하는 것도 굉장히 좋은 방법이라고 생각한다.

profile
I live in Seoul, Korea, Handsome

0개의 댓글