https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/
CyclicRotation coding task - Learn to Code - Codility
Rotate an array to the right by a given number of steps.
app.codility.com
문제
- 배열 A를 K번만큼 우측으로 shift했을 때, 배열을 구하는 문제
- 마지막 원소는 배열의 첫번째로 들어오는 방식
풀이
- java deque(데크)를 활용하는 방식으로 풀이
- A배열의 원소들을 deque에 입력
- K번 만큼 반복시키며 마지막 원소를 빼서 첫번째에 다시 삽입한 후 배열 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) {
// write your code in Java SE 8
Deque<Integer> deque = new LinkedList<Integer>();
for(int i:A){
deque.add(i);
}
// 3 8 9 7 6
for( int i=0; i<K; i++ ){
int lastVal = deque.pollLast();
deque.addFirst(lastVal);
}
Object[] arr = deque.toArray();
int[] answer = new int[arr.length];
for(int i=0; i<arr.length; i++ ){
answer[i] = (int)arr[i];
}
return answer;
}
}
마지막에 deque로 toArray() 메소드를 실행 시 Object[]로 나오는 부분을 더 매끄럽게 처리할 수 있는 방법을 찾아봐야겠다..
참고 사이트
[Java] Deque (덱/데크) 사용법 및 예제
Deque(덱/데크) 덱은 Double-Ended Queue의 줄임말로 큐의 양쪽에 데이터를 넣고 뺄 수 있는 형태의 자료구조를 의미한다. 하나의 자료구조에 큐(Queue)와 스택(Stack)을 합쳐 놓은 형태라고 생각하면 된다.
hbase.tistory.com
'코딜리티 문제풀이' 카테고리의 다른 글
Codility Lesson 03 - TapeEquilibrium( JAVA ) (0) | 2022.03.16 |
---|---|
Codility Lesson 03 - PermMissingElem( JAVA ) (0) | 2022.03.14 |
Codility Lesson 03 - FrogJmp( JAVA ) (0) | 2022.03.13 |
Codility Lesson 02 - OddOccurrencesInArray( JAVA ) (0) | 2022.03.13 |
Codility Lesson 01 - BinaryGap( JAVA ) (0) | 2022.03.09 |