코딩 테스트 (Java)/코딩 기초 트레이닝 (프로그래머스)

181924. 수열과 구간 쿼리 3

가지코딩 2025. 4. 4. 13:15

https://school.programmers.co.kr/learn/courses/30/lessons/181924

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제

정수 배열 arr와 2차원 정수 배열 queries이 주어집니다. queries의 원소는 각각 하나의 query를 나타내며, [i, j] 꼴입니다.

query마다 순서대로 arr[i]의 값과 arr[j]의 값을 서로 바꿉니다.

위 규칙에 따라 queries를 처리한 이후의 arr를 return 하는 solution 함수를 완성해 주세요.

 

제한사항

  • 1 ≤ arr의 길이 ≤ 1,000
    • 0 ≤ arr의 원소 ≤ 1,000,000
  • 1 ≤ queries의 길이 ≤ 1,000
    • 0 ≤ i < j < arr의 길이

 

입출력 예

arr queries result
[0, 1, 2, 3, 4] [[0, 3],[1, 2],[1, 4]] [3, 4, 1, 0, 2]

 

입출력 예 #1

  • 각 쿼리에 따라 arr가 다음과 같이 변합니다.
arr
[0, 1, 2, 3, 4]
[3, 1, 2, 0, 4]
[3, 2, 1, 0, 4]
[3, 4, 1, 0, 2]

 


풀이

class Solution {
    public int[] solution(int[] arr, int[][] queries) {
        int[] answer = arr.clone();
        int temp;
        
        for(int[] q: queries){
            temp = answer[q[0]];
            answer[q[0]] = answer[q[1]];
            answer[q[1]] = temp;
        }
        return answer;
    }
}

 

 

 


GitHub: https://github.com/gajicoding/coding_test/edit/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/0/181924.%E2%80%85%EC%88%98%EC%97%B4%EA%B3%BC%E2%80%85%EA%B5%AC%EA%B0%84%E2%80%85%EC%BF%BC%EB%A6%AC%E2%80%853

 

coding_test/프로그래머스/0/181924. 수열과 구간 쿼리 3 at main · gajicoding/coding_test

This is an auto push repository for Baekjoon Online Judge created with [BaekjoonHub](https://github.com/BaekjoonHub/BaekjoonHub). - gajicoding/coding_test

github.com


출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

 

코딩테스트 연습 | 프로그래머스 스쿨

개발자 취업의 필수 관문 코딩테스트를 철저하게 연습하고 대비할 수 있는 문제를 총망라! 프로그래머스에서 선발한 문제로 유형을 파악하고 실력을 업그레이드해 보세요!

school.programmers.co.kr