개발자식

[Codility Lesson2] CyclicRotation 본문

Algorithm/Codility

[Codility Lesson2] CyclicRotation

밍츠 2022. 6. 23. 23:01

2. CyclicRotation

 

Test results - Codility

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9,

app.codility.com

 

나의 풀이

- 배열을 복사하여 원본 배열에서 값을 가져와서 복사된 배열에 값을 바꾸고

- k만큼 이동하면 총 길이를 넘어가는 경우와 아닌 경우를 나누어서 계산

def solution(A, K):
    # write your code in Python 3.6
    temp = A.copy()

    if K==0 or len(A)==0:
        return A

    if K > len(A):
        K = K % len(A)

    for i in range(len(A)):
        if i+K < len(A):
            temp[i+K] = A[i]
        else:
            temp[i+K-len(A)] = A[i]


    return temp

* 주의 : K의 범위가 0부터이기 때문에 따로 처리하지 않으면 % 연산자 때문에 에러 발생

 

 

다른 풀이

1. 뒤에서 하나씩 꺼내서 앞에 넣기 (총 K번)

def solution(A, K):
    if A :
    	for i in range(K):
            a = A.pop()
            A.insert(0, a)

    return A

2. 인덱싱 

def solution(A, K):
    # write your code in Python 3.6
    if not (A and K):
        return A

    K = K % len(A)
    return A[-K:] + A[:-K]

- 여기서도 마찬가지로 0일때 주의

Comments