문제설명
정수가 담긴 배열 numbers와 문자열 direction가 매개변수로 주어집니다. 배열 numbers의 원소를 direction방향으로 한 칸씩 회전시킨 배열을 return하도록 solution 함수를 완성해주세요.
제안사항
- 3 <= numbers길이 <=20
- direction은 "left" or "right"
#include <string>
#include <vector>
using namespace std;
vector<int> solution(vector<int> numbers, string direction) {
vector<int> answer;
//left와 right 두가지 경우의 if문을 따로 만들었다.
if(direction == "left")
{
for(int i=0; i<numbers.size()-1; i++)
answer.push_back(numbers.at(i+1));
answer.push_back(numbers.at(0));
}
else if(direction == "right")
{
answer.push_back(numbers.back());
for(int i=1; i<numbers.size(); i++)
answer.push_back(numbers.at(i-1));
}
return answer;
}
vector를 사용할 줄 알아야 하는 문제
- v,push_back() : 벡터의 마지막에 변수 삽입
- v.at(i) : 특정 위치인 i 에서 접근
- v.size() : 벡터의 크기 반환
https://hwan-shell.tistory.com/119
C++ vector사용법 및 설명 (장&단점)
C++의 vector는 C++ 표준라이브러리(Standard Template Library)에 있는 컨테이너로 사용자가 사용하기 편하게 정의된 class를 말합니다. vector를 생성하면 메모리 heap에 생성되며 동적할당됩니다. 물론 속도
hwan-shell.tistory.com
더 쉽게 풀기
#include <algorithm>에 rotate()함수 사용
First 에서 Last 구간을 Middle을 기준으로 회전시킬때 사용.
n칸씩 밀거나, n칸씩 당겨와야 할때 유용하게 쓰인다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> numbers, string direction) {
if(direction =="left")
rotate(numbers.begin(),numbers.begin()+1,numbers.end());
else(direction =="right")
rotate(numbers.begin(),numbers.end()-1,numbers.end());
return numbers;
}
'Algorithm > Programmers' 카테고리의 다른 글
[프로그래머스] Lv.0 정수를 나선형으로 배치하기 c++ (0) | 2024.12.30 |
---|---|
[프로그래머스] Lv.3 정수 삼각형 c++ (0) | 2024.12.30 |
[프로그래머스] Lv.2 하노이의 탑 c++ (0) | 2024.12.29 |
[프로그래머스] Lv.2 카펫 c++ (0) | 2024.12.27 |
[프로그래머스] Lv.2 귤 고르기 c++ (0) | 2024.12.27 |