본문 바로가기
Develop/프로그래머스 (Cpp)

[프로그래머스] 배열 회전시키기 (C++)

by Tarra 2023. 3. 8.

배열 회전시키기 / Lv.0


문제  설명 )

정수가 담긴 배열 numbers와 문자열 direction가 매개변수로 주어집니다. 배열 numbers의 원소를 direction방향으로 한 칸씩 회전시킨 배열을 return하도록 solution 함수를 완성해주세요.

 

 

 

제한 사항 )

  • 3 ≤ numbers의 길이 ≤ 20
  • direction은 "left" 와 "right" 둘 중 하나입니다.

 

 

 

입출력 예 )

 

 

입출력 예 설명 )

입출력 예 #1

  • numbers 가 [1, 2, 3]이고 direction이 "right" 이므로 오른쪽으로 한 칸씩 회전시킨 [3, 1, 2]를 return합니다.

입출력 예 #2

  • numbers 가 [4, 455, 6, 4, -1, 45, 6]이고 direction이 "left" 이므로 왼쪽으로 한 칸씩 회전시킨 [455, 6, 4, -1, 45, 6, 4]를 return합니다.

 

 

풀이)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <vector>
#include <deque>
 
using namespace std;
 
vector<int> solution(vector<int> numbers, string direction) {
    deque<int> answer;
    
    // deque에 answer의 원소 집어넣기
    for(int i = 0; i < numbers.size(); i++)
    {
        answer.push_back(numbers[i]);
    }
    
    // direction에 따라 rotate
    if (direction == "right")
    {
        int temp = answer.back();
        answer.pop_back();
        answer.push_front(temp);
 
    }
    else if (direction == "left")
    {
        int temp = answer.front();
        answer.pop_front();
        answer.push_back(temp);
    }
    
    // 정답으로 제출할 result는 vector로 만들어 제출한다.
    vector<int> result(answer.begin(), answer.end());
    
    return result;
}
cs

출처 : https://school.programmers.co.kr/learn/courses/30/lessons/120844

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr