알고리즘 풀이 방법입니다.
문제(Problem) -> 생각(Think) -> 해결책(Solution) -> 리뷰(Review) 를 통해서 정리해서 작성합니다.
Problem📄

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

 

프로그래머스

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

programmers.co.kr


Think🤔

반복문 두개를 이용해서

2차원 배열을 구하고 replace개념으로 int를 바꿔준다!


Solution✍
import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        for(int i=0; i<commands.length; i++){
            int[] tmp = new int[commands[i][1] - commands[i][0]+1];
            int cnt = 0;
            for(int j=commands[i][0] - 1; j<=commands[i][1] - 1; j++){
                tmp[cnt] = array[j];
                cnt++;
            }
            Arrays.sort(tmp); // 정렬 후 값

            answer[i] = tmp[commands[i][2]-1]; // 마지막 값
        }
        
        return answer;
    }
}

Review🤩
int[] tmp = Arrays.copyOfRange(array, 2,6);

copyofRange를 사용하면 array의 인덱스 배열 요소 일부를 복사해서 가져올 수 있다.

	        int commands[][] = {{2,5,3},{4,4,1},{1,7,3}};
    	    	int array[] = {1,5,2,6,3,7,4};
        	int[] answer = new int[commands.length];
			
	        for(int i=0; i<commands.length; i++){
	            int[] tmp = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
	            
	            Arrays.sort(tmp); // 정렬 후 값
	            System.out.println(Arrays.toString(tmp));
	            answer[i] = tmp[commands[i][2]-1]; // 마지막 값
	        }

중간 부분을 이런식으로 줄일 수 있음


 

'Algorithm' 카테고리의 다른 글

[프로그래머스] 내적  (0) 2022.08.08
[프로그래머스] 실패율  (0) 2022.08.08
[프로그래머스] 3진법 뒤집기  (0) 2022.07.29
[프로그래머스] 두 개 뽑아서 더하기  (0) 2022.07.28
[프로그래머스] 2016년  (0) 2022.07.27

+ Recent posts