스택/큐
프로세스
def solution(priorities, location):
queue = [(i, p) for i, p in enumerate(priorities)] # 각 문서의 인덱스와 우선순위를 튜플로 묶어 큐에 저장
answer = 0 # 출력 순서를 저장하는 변수
while True:
cur = queue.pop(0) # 큐의 첫 번째 요소를 꺼냄
if any(cur[1] < q[1] for q in queue): # 현재 문서보다 우선순위가 높은 문서가 큐에 존재하는지 확인
queue.append(cur) # 있으면 현재 문서를 큐의 맨 뒤로 이동
else: # cur[1] >= q[1]
answer += 1 # 현재 문서를 출력
if cur[0] == location: # 현재 문서가 내가 요청한 문서이면
return answer # 출력 순서를 반환
큐 어떻게 쓰는지 모르겠어서 아예 못풀었다... 생각이 안나
이런 생각 어떻게 하는거지😢
첫 번째 예시는 이해가 갔는데 두 번째 이해가 안가서 gpt한테 물어보고 다시 생각해봤다. 만약 9를 pop하면 queue에 append를 안하니까 항상 1이 queue에 있는 값들보다 작지 않아진다. 그래서 answer에 계속 값이 증가하게 되고 그러다가 만약 찾는 location의 index면 answer을 반환한다.
enumerate
enumerate(순서가 있는 객체, start=0)
print(fruits)
#['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print(list(enumerate(fruits)))
#[(0, 'orange'), (1, 'apple'), (2, 'pear'), (3, 'banana'), (4, 'kiwi'), (5, 'apple'), (6, 'banana')]
any() : 하나라도 True인게 있으면 True
all() : 모두 True여야 True 반환
import java.util.*;
public class Solution {
public static int solution(int[] priorities, int location) {
// 큐를 사용하여 문서와 인덱스를 저장합니다.
LinkedList<int[]> queue = new LinkedList<>();
for (int i = 0; i < priorities.length; i++) {
queue.add(new int[]{i, priorities[i]});
}
int answer = 0;
while (true) {
// 큐의 첫 번째 요소를 꺼냅니다.
int[] cur = queue.poll();
boolean hasHigherPriority = false;
// 큐에 현재 문서보다 높은 우선순위의 문서가 있는지 확인합니다.
// python의 any 대신 직접 루프를 돌며 확인
for (int[] q : queue) {
if (cur[1] < q[1]) {
hasHigherPriority = true;
break;
}
}
if (hasHigherPriority) {
// 우선순위가 높은 문서가 있으면 현재 문서를 큐의 맨 뒤로 이동합니다.
queue.add(cur);
} else {
answer++;
if (cur[0] == location) {
return answer;
}
}
}
}
}
LinkedList 사용법
LinkedList<int[]> queue = new LinkedList<>();
: LinkedList를 생성합니다. 여기서 LinkedList는 int[] 배열을 요소로 갖습니다.
for (int i = 0; i < priorities.length; i++)
: priorities 배열의 길이만큼 반복합니다.
queue.add(new int[]{i, priorities[i]});
: 현재 인덱스 i와 priorities[i] 값을 갖는 int[] 배열을 생성하여 queue에 추가합니다.
// 출력하고 싶으면 이렇게 ...
for (int[] q : queue) {
System.out.println("Index: " + q[0] + ", Priority: " + q[1]);
}
queue.poll()
큐의 첫번째 요소를 삭제 및 반환한다. 만약 큐가 비어있으면 null을 반환한다. remove는 만약 큐가 비어있으면 예외가 발생한다.