[재귀] 배열 뒤집기

박채은·2022년 11월 18일
0

코딩테스트

목록 보기
1/52

문제

배열을 입력받아 순서가 뒤집힌 배열을 리턴해야 합니다.(재귀 사용)

[코플릿 - reverseArr]


코드

public int[] reverseArr(int[] arr){
    // 가장 맨 뒤에 있는 요소 -> head[]
	// 맨 뒤 요소를 제거한 나머지 배열 -> tail[]
    // 탈출 조건
	if(arr.length==0) return new int[]{};
	
	int[] head = Arrays.copyOfRange(arr, arr.length-1, arr.length);
	int[] tail = Arrays.copyOfRange(arr, 0, arr.length-1);
		
	int[] result = reverseArr(tail);
    
	// head, result 순으로 합치기	
	int[] merge = new int [head.length + tail.length];
	System.arraycopy(head,0, merge, 0, head.length);
	System.arraycopy(result, 0, merge, 1, result.length);
	return merge;
} 
public static int[] reverseArr(int[] arr) {
        // 탈출 조건
        if (arr.length == 0) return new int[]{};

        // 가장 앞에 있는 요소 -> head[]
        // 나머지 -> tail[]
        int head[] = Arrays.copyOfRange(arr, 0, 1);
        int tail[] = Arrays.copyOfRange(arr, 1, arr.length);

        int result[] = reverseArr(tail);

        // result, head 순으로 합치기
        int merge[] = new int[result.length + head.length];
        System.arraycopy(result, 0, merge, 0, result.length);
        System.arraycopy(head, 0, merge, result.length, 1);
        return merge;
}

재귀 과정

[1,2,3,4,5]이 인자로 들어왔다고 가정해보자.

재귀 과정을 다음과 같이 표현할 수 있을 것이다.

0개의 댓글