MapleStory Finger Point

🏃‍♀️programmers/Java

프로그래머스 - java 배열 뒤집기

HYEJU01 2024. 5. 15. 14:57
체감 Level : ★☆☆
Review: 반복문을 통해서 쉽게 풀 수 있다 ! 방법이 다양하다 !

 

💡 배열을 거꾸로 뒤집으면 되는 문제이다.

 

for 문 :: 인덱스를 이용해서 순행 <-> 역행 시키기 !!

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length];
    
        for (int i = 0 ; i < num_list.length; i++){
            answer[i] = num_list[num_list.length-1-i];
        }
        
        return answer;
    }
}

 

while 문 이용 :: 기존 배열을 수정한다,   메모리를 더 효율적으로 사용한다고함 !!

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = {};
    
        int l = 0;
        int r = num_list.length - 1;

        while (l < r) {
            int temp = num_list[l];
            num_list[l] = num_list[r];
            num_list[r] = temp;

            l++;
            r--;
        }
        
        return num_list;
    }
}