Post

[Programmers] #120844 - 배열 회전시키기 [Java][C++][Python]

[Programmers] #120844 - 배열 회전시키기 [Java][C++][Python]

문제 링크


1. 아이디어

배열의 원소를 지정한 방향으로 한 칸씩 회전시킨 배열을 반환하는 문제다. 왼쪽으로 한 칸 돌리면 모든 원소가 한 칸씩 앞으로 당겨지고 맨 앞의 원소가 맨 뒤로 가며, 오른쪽이면 모든 원소가 한 칸씩 뒤로 밀리고 맨 뒤의 원소가 맨 앞으로 온다. 따라서 한쪽 끝의 원소 하나를 반대쪽 끝으로 옮기고 나머지를 한 칸씩 어긋나게 옮기면 된다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public int[] solution(int[] numbers, String direction) {
        int[] arr = new int[numbers.length];
        if (direction.equals("left")) {
            System.arraycopy(numbers, 1, arr, 0, numbers.length - 1);
            arr[numbers.length - 1] = numbers[0];
        } else {
            System.arraycopy(numbers, 0, arr, 1, numbers.length - 1);
            arr[0] = numbers[numbers.length - 1];
        }

        return arr;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(vector<int> numbers, string direction) {
    if (direction == "left") {
        rotate(numbers.begin(), numbers.begin() + 1, numbers.end());
    } else {
        rotate(numbers.begin(), numbers.end() - 1, numbers.end());
    }

    return numbers;
}

std::rotate로 두 번째 인자의 원소가 새 시작이 되도록 구간을 회전시켰다.

1
2
3
4
5
def solution(numbers, direction):
    if direction == "left":
        return numbers[1:] + numbers[:1]
    else:
        return numbers[-1:] + numbers[:-1]

This post is licensed under CC BY 4.0 by the author.