Recent Posts
													
											
												
												
													Recent Comments
													
											
												
												
											
									HEROJOON 블로그(히로블)
[Codility] [Lesson2] CyclicRotation JAVA 본문
반응형
    
    
    
  
문제
배열을 오른쪽으로 N번 이동하기
ex)
A = [3, 8, 9, 7, 6]
K = 3
가 주어졌을때
[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]
3번 로테이션 돌렸으니까 결과는 [9, 7, 6, 3, 8] 이다.
풀이
public int[] solution(int[] A, int K) {
    if (A == null || A.length == 0) {
        return A;
    }
    int tempNum = 0;
    for (int i = 0; i < K; i++) {
        tempNum = A[0];
        A[0] = A[A.length - 1];
        for (int j = A.length - 1; j > 0; j--) {
            if (j == 1) {
                A[j] = tempNum;
                continue;
            }
            A[j] = A[j-1];
        }
    }
    return A;
}
테스트
- 주어진 값
int[] A = {3, 8, 9, 7, 6};
int K = 3;
- 결과 값
[9, 7, 6, 3, 8]
반응형
    
    
    
  '코딩테스트' 카테고리의 다른 글
| [Codility] [Lesson3] PermMissingElem JAVA (1) | 2020.11.04 | 
|---|---|
| [Codility] [Lesson3] FrogJmp JAVA (1) | 2020.11.04 | 
| [Codility] [Lesson2] OddOccurrencesInArray JAVA (0) | 2020.11.04 | 
| [Codility] [Lesson1] BinaryGap JAVA (0) | 2020.11.04 | 
			  Comments
			
		
	
               
           
					
					
					
					
					
					
				 
             
								 
								 
								