코딜리티 프로그래머 두 번째 Lesson 문제인 CyclicRotation 은 정렬되지 않은 n개의 숫자 배열(array)에 있는 값들을 하나씩 오른쪽으로 옮기는데 파라미터로 몇번 옮겨야 하는지(k)도 같이 주어집니다. (int[] array, int k)
옮겨야되는 수(k)가 3이라면 총 3번 오른쪽으로 옮기면 됩니다. 마지막에 있는 값은 첫 번째 자리로 옮기면 됩니다.
ex)[1,2,3,4,5] -> [5,1,2,3,4] , [5,1,2,3,4] -> [4,5,1,2,3] , [4,5,1,2,3] -> [3,4,5,1,2]
java로 구현을 하였는데, 의식에 흐름대로 풀고난 후에 다른 사람의 코드를 보고 자괴감이 들었습니다..
코드를 짤 때, 조금 더 생각하면서 짜야겠다고 다시 한 번 느끼게 됬습니다..
1. 의식의 흐름대로 짠 java 코드 입니다.
// 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) {
// write your code in Java SE 8
int len = A.length;
int[] A2 = new int[len];
for(int i=0;i<K;++i){
for(int j=0;j<len;++j){
if(j == (len-1)) {
A2[0] = A[j];
break;
}
A2[j+1] = A[j];
}
for(int k=0;k<len;++k){
A[k] = A2[k];
}
}
return A;
}
}
2. 다른 사람의 사이트에서 가지고 온 코드입니다. (출처: blog.naver.com/PostView.nhn?blogId=netrance&logNo=220690184441)
// 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) {
// write your code in Java SE 8
//System.out.println(A.length);
int[] B = new int[A.length];
for(int i = 0; i < A.length; i++){
B[( i + K ) % A.length] = A[i];
}
return B;
}
}
공부하면서 위 블로그를 앞으로 많이 참고해야할 것 같습니다.
'IT > 알고리즘' 카테고리의 다른 글
| [코딜리티] Binary Gap (0) | 2018.03.11 |
|---|