Post

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

배열의 원소를 좌우 한 칸씩 회전시킨 결과를 구하는 워밍업 문제.

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

문제 링크


1. 아이디어

한 칸 회전이므로 끝에 있는 원소 하나만 반대쪽 끝으로 옮기면 나머지는 순서를 유지한 채 한 칸씩 밀린다.

direction"left"면 맨 앞 원소를 맨 뒤로 보내고, "right"면 맨 뒤 원소를 맨 앞으로 보낸다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = numbers의 길이)


3. 코드

풀이 [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(first, middle, last)[first, last) 구간을 왼쪽으로 돌려 middle이 가리키던 원소가 맨 앞에 오도록 만든다.

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.