Java - [프로그래머스]42587 - 프로세스

Paek·2023년 8월 12일
0

코테공부 자바

목록 보기
13/25

출처

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

문제


우선순위에 따라 큐에 담긴 프로세스를 실행하고, location위치에 있는 프로세스가 몇번째에 실행되는지 구하는 문제입니다.

풀이 : 우선순위 큐 사용

프로세스를 우선순위에 따라 다루기 위해 우선순위 큐를 선언합니다. 내부에는 for문을 선언하여 priorities를 순차적으로 탐색합니다. 현재 큐 제일 앞에 위치한 우선순위와 priorities에 담긴 우선순위를 비교하고, 일치하는게 있다면 poll()을 통해 제거해주고 answer을 증가시킵니다. 이 과정을 반복하여 원하는 위치의 원소를 찾으면 return해줍니다.

코드

//PriorityQueue를 이용한 풀이
import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
		
		for(int num : priorities) {
			pq.add(num);
		}
		while(!pq.isEmpty()) {
			for(int i=0; i<priorities.length; i++) {
				if(priorities[i] == pq.peek()) {
					pq.poll();
					answer++;
					if(i == location)
						return answer;
				}
			}
		}  
        return answer;
    }
}

풀이 : ArrayList사용

우선순위와 인덱스를 모두 기억해야 한다고 생각하여 처음 풀때 풀었던 방식입니다. 정렬을 통해 우선순위를 놓았고, MAX값을 매번 구해 우선순위를 비교해나가는 방식으로 풀었습니다. 또한 위치 정보를 따로 가지고 있도록 location변수를 사용하였습니다.

코드

import java.util.*;
class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        List<Integer> list = new ArrayList<>();
        for(int x : priorities) {
            list.add(x);
        }
        while(location >= 0) {
            System.out.println(list.get(0));
            int max = Collections.max(list);
            if(list.get(0) >= max) {
                list.remove(0);
                location--;
                answer++;
                if(location < 0) {
                    break;
                }
            } else {
                int tmp = list.get(0);
                list.remove(0);
                list.add(tmp);
                location--;
                if(location < 0) {
                    location = list.size()-1;
                }
            }
        }
        return answer;
    }
}
profile
티스토리로 이전했습니다. https://100cblog.tistory.com/

0개의 댓글