알고리즘/백준

[백준] 2164 - 자바

삼록이 2025. 7. 21. 09:29

첫번째 풀이

/*
        1.큐에 1~n까지 담는다.
        2.홀수번째일 때는 가장 앞에 있는 걸 버린다.
        3.짝수번째일 때는 가장 앞에 있는 걸 맨 뒤로 옮긴다.
         */

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        Queue<Integer> queue = new LinkedList<>();

        for(int i=1; i<n+1; i++){
            queue.add(i);
        }

       int count =1;
       while(queue.size()>1){
           if(count % 2 ==1){
               queue.poll();
           } else{
               int a = queue.poll();
               queue.add(a);
           }
           count++;
       }
        System.out.println(queue.poll());
    }
}

두번째 풀이.

첫번째 풀이는 짝수번째,홀수번째 차례차례 진행한거였지만 사실 굳이 짝수번째 홀수번째 나눌 필요도 없다.

아래처럼 한번에 가능하다.

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        Queue<Integer> q = new LinkedList<>();

        for(int i=1; i<=n; i++){
            q.offer(i);
        }

        while(q.size()>1){
            q.poll();
            q.offer(q.poll());
        }
        System.out.println(q.poll());
    }
}