CyclicRotation
1 | 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, 7] (elements are shifted right by one index and 6 is moved to the first place). |
방법
배열 A의 크기를 N으로 하였을 때 N의 요소들을 K만큼 옮기기 위하여 N의 요소들의 index값에 K를 더하여 해결
N의 inedx+K의 값이 N의 전체 길이보다 클 경우 0부터 증가시킴
위 방법을 그대로 사용 할 경우 반복이 많아짐
N의 길이가 5이고 K가 3이라고 할 경우 N[0]의 값은 N[3]이 되며 N[4]는 N[7]이 되어 0부터 다시 계산하면 N[2]가 됨
K의 값이 N의 길이보다 많이 클 경우를 생각하여 %연산을 이용
즉 본래 index+K의 값을 N의 길이로 나눈 나머지 값을 새로운 index로 사용
N[4]는 N[7]되고 7%5=2가 됨
코드
1 | import copy |
추가
오늘 python을 배운김에 python으로 작성해봄