728x90
SMALL
https://www.acmicpc.net/problem/1021
1021번: 회전하는 큐
첫째 줄에 큐의 크기 N과 뽑아내려고 하는 수의 개수 M이 주어진다. N은 50보다 작거나 같은 자연수이고, M은 N보다 작거나 같은 자연수이다. 둘째 줄에는 지민이가 뽑아내려고 하는 수의 위치가
www.acmicpc.net
LinkedList를 이용하여 풀었습니다.
Queue와 LinkedList에 대해서 모른다면 아래글을 참고하셔도 됩니다.
https://je-pa.tistory.com/entry/%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0-Queue
[자료구조] Queue
목표 인터페이스 Queue의 관 메소드를 알아보자. Queue를 LinkedList로 구현해 보자. Queue 인터페이스 자바(Java)에서 Queue는 데이터를 저장하고 관리하는 자료 구조로, FIFO(First-In-First-Out) 원칙을 따릅니
je-pa.tistory.com
아래는 두번째 예제의 과정을 손으로 적어본 내용입니다.
필자의 답
package zerobase.twoweek;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
public class 회전하는큐 {
public static void main(String[] args) throws Exception{
LinkedList<Integer> list = new LinkedList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] arr2 = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int count = 0;
LinkedList<Integer> list = new LinkedList<>();
for(int i=1; i<=arr[0] ; i++){
list.add(i);
}
for(int i : arr2){
int size = list.size();
int index = list.indexOf(i);
if(index <= size/2){ // 요소의 index가 중간 미만일 경우 뒤에 요소를 앞으로 보내줍니다.
while(list.peek()!=i){
list.add(list.remove());
count++;
}
}else{ // 요소의 index가 중간 이상일 경우 뒤에 요소를 앞으로 보내줍니다.
while(list.peek()!=i){
list.addFirst(list.removeLast());
count++;
}
}
list.remove();
}
System.out.println(count);
}
}
728x90
LIST
'Coding test > Baekjoon' 카테고리의 다른 글
[백준][JAVA] 26008번: 해시 해킹 (0) | 2023.08.12 |
---|---|
[백준][JAVA] 10818번: 최소, 최대 (0) | 2023.08.09 |
[백준][JAVA] 11053번: 가장 긴 증가하는 부분 수열 (0) | 2023.08.01 |
[백준][JAVA] 2193번: 이친수 (0) | 2023.07.31 |
[백준][JAVA] 25556번: 포스택 (0) | 2023.02.14 |