프로그래머스 Level1-5 | 배열의 복사와 정렬

yuriyaam·2021년 1월 26일
0
post-thumbnail

java.util.Arrays Class를 배워보자

java.util.Arrays 유틸리티 클래스를 사용하면 배열(Array)을 정렬, 복제하거나, List로 변환 하는 등의 작업을 쉽게 처리 할 수 있다. 또한 Arrays 클래스의 모든 메소드는 클래스 메소드(static method)이므로, 객체를 생성하지 않고도 바로 사용할 수 있다.

copyOfRange(arr, n1, n2) 메소드

  • arr : 이 배열을 복사해라.
  • n1 : index n1부터
  • n2 : index n2의 전까지

sort(arr) 메소드

  • arr : arr을 오름차순 정렬해라.

문제

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.

예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면

array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.

코드

static int[] solution(int[] array, int[][] commands) {
  int[] answer = {};
  int[] arr = {};

  answer = new int[commands.length];

  for (int i = 0; i < commands.length; i++) {
	int num = commands[i][1] - commands[i][0] + 1;
	arr = new int[num];

	int cnt = 0;
	for (int j = commands[i][0] - 1; j < commands[i][1]; j++) {
	  arr[cnt++] = array[j];
	}

	int temp = 0;
	for (int j = 0; j < arr.length - 1; j++) {
	  for (int y = j + 1; y < arr.length; y++) {
	    if (arr[j] > arr[y]) {
		temp = arr[j];
		arr[j] = arr[y];
		arr[y] = temp;
	    }	// if end
	  }	// for end
	}	// for end

	answer[i] = arr[commands[i][2] - 1];
  }
  return answer;
}

이게 내가 푼건데, arrays 클래스의 메소드를 사용하면 간단하게 풀이가 가능하다.

Arrays 메소드를 사용한 코드

static int[] solution2(int[] array, int[][] commands) {
  int[] answer = {};

  answer = new int[commands.length];

  for (int i = 0; i < commands.length; i++) {
	int[] temp = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
	Arrays.sort(temp);
	answer[i] = temp[commands[i][2] - 1];
  }
  return answer;
}

참고 1 ) https://norwayy.tistory.com/85
참고 2 ) https://ifuwanna.tistory.com/232

0개의 댓글