sort - K번째수

콜 파머가 될 남자·2024년 1월 12일
0
post-thumbnail

첫 번째 풀이

public int[] solution(int[] array, int[][] commands) {
	ArrayList<Integer> result = new ArrayList<>();

	for (int[] command : commands) {
      ArrayList<Integer> temp = new ArrayList<>();

      int start = command[0];
      int end = command[1];
      int k = command[2];


      for (int i = start-1; i < end; i++) temp.add(array[i]);

      Arrays.sort(temp.stream().mapToInt(i -> i).toArray());

      result.add(temp.get(k-1));
	}

	return result.stream().mapToInt(i -> i).toArray();
}

그렇게 어렵지 않은 정렬 문제라 생각한다.
근데 처음 풀이에서 Arrays.sort 를 사용한 정렬을 할 때 문제가 발생했다.

stream 을 이용해서 바로 array로 바꾸고 sort를 했는데 이렇게 하니 원하는 결과값이 나오지 않았다.

위 정렬을

Collections.sort(temp);

ArrayList인 temp를 바로 Colletions 정렬을 해주니 원하는 값이 나왔다

왜 stream을 이용한 array로 바꿔서 정렬했을 때는 풀리지 않았을까?

그 이유는 temp list를 배열로 바꿔서 정렬을 했을 뿐이지,
직접적으로 temp list는 정렬을 하는것은 아니다.

int idx = 0;
Arrays.sort(temp.stream().mapToInt(i -> i).toArray());

for (Integer integer : temp) {
	System.out.println(idx++ +"번째 temp 원소 =" + integer);
}

위 처럼 직접적으로 list를 sort를 한 것이 아니기 때문에 정렬이 되지 않은 모습을 볼 수 있다.

배열과 리스트를 정렬하며 문제를 풀이할 때 주의하자

profile
콜 파머가 개발자라면 사회적 인지도는 어느 정도일까

0개의 댓글