본문 바로가기
코딩테스트 연습/프로그래머스 Lv.0

프로그래머스 코딩테스트 lv.0 - 배열 회전시키기 (Java)

by 트레비봄 2023. 8. 4.
728x90

문제 설명 및 입출력 예시

class Solution {
    public int[] solution(int[] numbers, String direction) {
        if (numbers == null || numbers.length == 0) {
            return numbers;
        }
        
        int length = numbers.length;
        int[] answer = new int[length];
        System.arraycopy(numbers, 0, answer, 0, length);
        // numbers 배열 요소 -> answer 배열로 복사.
        
        if ("right".equals(direction)) {
            // 오른쪽으로 회전
            int temp = answer[length - 1];
            for (int i = length - 1; i > 0; i--) {
                answer[i] = answer[i - 1];
            }
            answer[0] = temp;
        } else if ("left".equals(direction)) {
            // 왼쪽으로 회전
            int temp = answer[0];
            for (int i = 0; i < length - 1; i++) {
                answer[i] = answer[i + 1];
            }
            answer[length - 1] = temp;
        } 
        return answer;
 // direction 값이 "right" 또는 "left"가 아닌 경우, 원본 배열을 그대로 리턴
    }
}

* 배열 회전시키기 라는 문제이다.

* 와 어렵다. 이게 연습문제에 속해있는게 신기할 정도.. 내가 못 푸는 것 같다만;;

* gpt 한테 도움을 받아서 코드를 봤는데 이해가 되는것 같으면서도 내일 다시 문제 풀라고하면 풀 수 있을까?? 싶다..

 

230804 학습.

728x90