Queue_마지막 남은 한 사람
✅ 마지막 남은 한 사람 구하기
n명의 사람들이 원으로 둥글게 앉아 있다.
돌아가면서 처음 사람부터 1부터 n까지 외치는데, k 숫자를 외친 사람은 제외된다.
그러면 남은 사람들끼리 또 1부터 n-1 까지 외치고, k 숫자를 외친 사람은 또 제외된다.
이것을 반복했을 때 마지막 남는 한 사람을 구하세요
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Main {
public int solution(int n, int k){
int answer= 0;
Queue<Integer> queue= new LinkedList<>();
for(int i=1; i<n+1; i++){
queue.offer(i);
}
while(!queue.isEmpty()){
for(int j=1; j<k; j++) queue.offer(queue.poll());
queue.poll();
if(queue.size()==1) answer= queue.poll();
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int k= sc.nextInt();
System.out.print(T.solution(n, k));
}
}
//⭐️input:
//8 3
//⭐️output:
//7
🔵 ThingsILearned
✔️ 아래 내가 짠 코드도 정답이지만, count
라는 변수를 사용해서 count
가 k가 되면 queue.poll();
하도록 하였다.
그런데 강사님의 코드를 보니 그럴 필요가 없었다.
앞의 숫자들을 뒤에 더해버리고
다 poll
해버리면 count
라는 변수가 필요가 없다.
🟢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Main {
public int solution(int n, int k){
int answer= 0;
Queue<Integer> queue= new LinkedList<>();
for(int i=1; i<n+1; i++){
queue.offer(i);
}
while(queue.size() != 1){
int count=1;
for(int j=1; j<k; j++){
count++;
int num= queue.peek();
queue.poll();
queue.offer(num);
if(count==k) queue.poll();
}
}
answer= queue.peek();
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int k= sc.nextInt();
System.out.print(T.solution(n, k));
}
}
This post is licensed under CC BY 4.0 by the author.