본문 바로가기
ALGORITHMS/SOLUTION

[프로그래머스: PYTHON] 배열회전시키기

by alasdkfm 2023. 5. 24.

목차

문제링크 :

 

프로그래머스

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

programmers.co.kr

 

문제 :

배열 회전시키기

문제 설명

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

 

제한사항

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

입출력 예

numbers kdirection result
[1, 2, 3] "right" [3, 1, 2]
[4, 455, 6, 4, -1, 45, 6] "left" [455, 6, 4, -1, 45, 6, 4]

입출력 예 설명 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합니다.

 

풀이과정

문제풀이 로직

IF, direction = "right" 이라면

       int 배열에 numbers\[-1\] 값 삽입 후, numbers\[0:-1\] 추가

ELSE, direction = "left" 라면

      int 배열에 numbers[1:-1] 추가 후, 마지막에 numbers[0]값 추가 

 

내 풀이

class Solution {
    public int[] solution(int[] numbers, String direction) {
        int len = numbers.length;
        int[] answer = new int [len];

        if (direction.equals("right"))
        {
            answer[0] = numbers[len-1];
            for (int i =1 ; i<len; i++)
                answer[i] = numbers[i-1];
        }
        else
        {
            for(int i=0; i<len-1; i++)
                answer[i] = numbers[i+1];
            answer[len-1] = numbers[0];
        }
        return answer;
    }
}

다른사람 풀이

list 자료구조 활용.

  1. nt배열 → List로 변환
  2. list.add()[# list.add( 인덱스, 삽입할 값 ); ] 사용
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Solution {
    public int[] solution(int[] numbers, String direction) {
        List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());

        if (direction.equals("right")) {
            list.add(0, list.get(list.size() - 1));
            list.remove(list.size() - 1);
        } else {
            list.add(list.size(), list.get(0));
            list.remove(0);
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

 

𝚂𝚘𝚞𝚛𝚌𝚎 𝚌𝚘𝚍𝚎

 

GitHub - xnsl291/Algorithms-study: 알고리즘 공부하며 풀었던 코드들을 업로드 하는 곳

알고리즘 공부하며 풀었던 코드들을 업로드 하는 곳 . Contribute to xnsl291/Algorithms-study development by creating an account on GitHub.

github.com

 

'ALGORITHMS > SOLUTION' 카테고리의 다른 글

[프로그래머스:JAVA] 2차원으로 만들기  (0) 2023.05.24
[프로그래머스:PYTHON] 공던지기  (0) 2023.05.24
[백준:JAVA] 단어수학  (0) 2023.05.23
[백준:PYTHON] 단어 수학  (0) 2023.05.23
[백준] 1004_어린왕자  (0) 2023.02.20