🔮문제
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).
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function:
vector<int> solution(vector<int> &A, int K);
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
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]
🔮풀이
A 벡터의 마지막 원소를 pop 한 후 맨 앞에 insert를 해주었다.
이 과정을 K번 만큼 반복 수행.
예외처리 !!!! A 벡터가 비어있을 경우를 생각해야했다.
🔮코드
#include <algorithm>
vector<int> solution(vector<int> &A, int K) {
//A벡터의 원소가 없으면 그대로 A 리턴
if(A.size() == 0)
return A;
while(K--){
int x = A.back();
A.pop_back();
A.insert(A.begin(), x);
}
return A;
}
'코딩 테스트' 카테고리의 다른 글
[Codility] Lesson3. FrogJmp (C++) (0) | 2021.02.23 |
---|---|
[Codility] Lesson1. BinaryGap (C++) (0) | 2021.02.23 |
[Codility] Lesson2. OddOccurrencesInArray (C++) (0) | 2021.02.22 |
[프로그래머스] 단어 변환 (C++) (0) | 2021.02.18 |
[프로그래머스] 가장 먼 노드 (C++) (0) | 2021.02.18 |
댓글