정수 N개로 이루어진 배열 A가 주어진다.

배열의 회전(rotation)이란, 배열의 각 원소가 오른쪽으로 한 칸씩 이동하고 마지막 원소가 맨 앞자리로 이동하는 것을 의미한다.

예를 들어, 배열 A = [3, 8, 9, 7, 6]을 한 번 회전시키면 [6, 3, 8, 9, 7]이 된다.

목표는 배열 A를 K번 회전시키는 것이다. 즉, 배열의 각 원소가 오른쪽으로 K번 이동해야 한다.

함수를 작성하라:

class Solution { public int[] solution(int[] A, int K); }

이 함수는 정수 배열 A와 정수 K가 주어졌을 때, 배열 A를 K번 회전시킨 결과를 반환해야 한다.

 

예시 1
A = [3, 8, 9, 7, 6], K = 3
반환값: [9, 7, 6, 3, 8]
회전 과정:
[3, 8, 9, 7, 6] → [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] → [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] → [9, 7, 6, 3, 8]

 

예시 2
A = [0, 0, 0], K = 1
반환값: [0, 0, 0]

 

예시 3
A = [1, 2, 3, 4], K = 4
반환값: [1, 2, 3, 4]

 

조건

  • N과 K는 [0..100] 범위의 정수
  • 배열 A의 각 원소는 [−1,000..1,000] 범위의 정수
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class CyclicRotation
{
    public int[] solution(int[] A, int K)
    {
        int arrayLength = A.Length;
 
        if (arrayLength == 0)
            return A;
 
        int[] result = new int[arrayLength];
 
        // K가 배열 길이와 동일하면 제자리회전..
        // 그러므로 K가 배열 길이보다 클 경우 나머지 연산을 통해 회전 수를 줄인다.
        int rotateCount = K % arrayLength;
 
        for (int i = 0; i < arrayLength; i++)
        {
            int rotatedIndex = GetRightRotatedIndex(i, rotateCount, arrayLength);
            result[rotatedIndex] = A[i];
        }
 
        return result;
    }
 
    private int GetRightRotatedIndex(int currentIndex, int rotateCount, int arrayLength)
    {
        // 오른쪽 회전시 현재인덱스에서 회전 수만큼 오른족으로 밀면 된다.
        int rotatedIndex = currentIndex + rotateCount;
 
        // 인덱스가 범위 넘어설 경우 나머지 연산
        if (rotatedIndex >= arrayLength)
            rotatedIndex %= arrayLength;
 
        return rotatedIndex;
    }
 
    // 번외 : 왼쪽 회전
    private int GetLeftRotatedIndex(int currentIndex, int rotateCount, int arrayLength)
    {
        // 왼쪽 회전시
        int rotatedIndex = currentIndex - rotateCount;
 
        // 음수가 되면 배열 길이 더해주면됨
        if (rotatedIndex < 0)
            rotatedIndex += arrayLength;
 
        return rotatedIndex;
    }
}
cs

'코딜리티 > Lesson' 카테고리의 다른 글

TapeEquilibrium (누적합 + 이항)  (0) 2025.09.15
PermMissingElem (등차수열)  (0) 2025.09.14
FrogJmp  (0) 2025.09.14
OddOccrurrencesInArray (짝 없는 원소)  (0) 2025.09.13
BinaryGap (이진 갭)  (0) 2025.09.13

+ Recent posts