[Codility] 02.CycleRotation - Array (Python)

Song_Song·2021년 12월 9일
0

https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/

배열 A가 주어졌을 때, 모든 배열 인자들을 K만큼 오른 쪽으로 회전시킨 결과를 리턴하는 문제.

A = [3, 8, 9, 7, 6]
K = 1 일 때, A = [6, 3, 8, 9, 7]
K = 2 일 때, A = [7 ,6, 3, 8, 9]
K = 3 일 때, A = [9, 7 ,6, 3, 8] 이다.

각 값들이 K 번 움직이고, 배열의 인덱스 범위를 넘으면 다시 처음 인덱스로 돌아오게 된다.
이 원리를 이용하면, 배열의 각 인덱스는 '(index+ K) % A의 길이' 번째 인덱스로 이동하게 된다.

즉 new_list[(index+ K) % A.length] = A[index] 의 식이 나온다.

나의 풀이

def solution(A, K):
    # write your code in Python 3.6
    ans = [0 for i in range(len(A))]

    for i in range(len(A)):
        new_index = (i+K) % len(A)
        ans[new_index] = A[i]

    return ans

    pass
profile
성장을 위한 정리 블로그

0개의 댓글