[java] 코딜리티 lessons2 CyclicRotation

[java] 코딜리티 lessons2 CyclicRotation

풀이 방법:

배열 A의 길이를 K로 나누어 나머지만 남긴다.(몫 만큼은 그냥 돌기 때문!)

그리고 A의 길이만큼 for문을 돌면서 A의 길이에서 그 값을 뺀(A.length-length) 값의 인덱스부터 A에서 빼내 res 배열로 넣는다.

단, 인덱스가 A길이를 넘었을 경우 인덱스를 0으로 처리하여 0번 인덱스부터 또 넣도록 해준다.

주의:

A가 빈 배열일 경우를 생각하지 못해서 /by zero 에러가 났었다!

처음에 아예 확인해서 바로 return 해주기!

// you can also use imports, for example: // import java.util.*; // you can write to stdout for debugging purposes, e.g. // System.out.println("this is a debug message"); class Solution { public int[] solution(int[] A, int K) { if(A.length == 0) return A; int[] res = new int[A.length]; int length = K % A.length; for(int i=0, l=A.length-length; i= A.length) l=0; res[i] = A[l++]; } return res; } }

For example, given A = [3, 8, 9, 7, 6] K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[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]

For another example, given

A = [0, 0, 0] K = 1

the function should return [0, 0, 0]

Given

A = [1, 2, 3, 4] K = 4

the function should return [1, 2, 3, 4]

from http://sthtoprve.tistory.com/9 by ccl(A) rewrite - 2021-11-11 02:02:17