본문 바로가기
Coding test/Programmers

[프로그래머스][JAVA] 프로세스

by jepa 2023. 8. 13.
728x90
SMALL

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

큐를 구현하고 있는 LinkedList를 이용하여 list에 int배열을 넣어주었다.

 

int배열을 넣어준 이유는 그냥 우선순위와 처음의 index값을 같이 넣어주기 위함이었다.

따로 클래스로 만들어 우선순위와 index를 묶어서 인스턴스로 생성해 넣어주는 것이 더 좋을 것 같긴하다.

 

그냥 편의상 int배열을 넣었다.

 

넣어준 다음, 우선순위가 1~9인점을 이용하여 arr배열 10사이즈로 할당 후 우선순위에 해당하는 index 값을 올려주어 각 우선순위의 개수를 세어주었다.

우선 순위가 높은 것을 먼저 빼내야하기 때문에 index 9부터 순차적으로 찾아주었다.
arr[index]가 0이면 해당하는 우선순위가 없기 때문에 다음으로 넘어가고자 index--;를 해주었고

arr[index]가 0이 아니라면 해당 우선순위를 가진 요소를 찾을 때(=peek() == index (=찾고있는 우선순위)) 까지

remove와 add를 이용하여 넘겨주었다.

 

peek을 했을 때 우선순위와 같다면 while을 벗어나 remove를 진행해준다.

remove를 했다는 것은 실행을 시켰다는 것이기 때문에 count++을 해주었다.

 

그리고 이때 remove를 한 값이 location과 같으면 break;를 해주어 종료하고 count를 반환해준다.

import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
LinkedList<int[]> list = new LinkedList<>();
int[] arr = new int[10];
for(int i=0; i<priorities.length ; i++){
arr[priorities[i]]++;
list.add(new int[]{priorities[i], i});
}
int index = 9;
int count = 0;
while(index != 0){
if(arr[index] == 0){
index--;
}else{
while(list.peek()[0] != index){
list.add(list.remove());
}
int play = list.remove()[1];
count++;
if(play == location){
break;
}
arr[index]--;
}
}
return count;
}
}
728x90
LIST