코딩테스트
정렬
Ark B
2025. 4. 22. 17:32
문제에서 int[] 이렇게 주어진 경우에서
만약 순서대로 정렬하는 경우에는 매우 간단하게 처리할 수 있음.
public static int[] sort(int[] arrays)
{
return Arrays.sort(arrays);
}
하지만 역방향으로 정렬해야하는 경우에는
public static int[] reverseSort(int[] arrays){
Integer[] result = Arrays.stream(arrays)
.boxed() -> primitive type, Integer로 wrapper된 상태
.distinct()-> 중복값 제거
.toArray(Integer[]::new);
Arrays.sort(result, Collections,reverseOrder()); // 내림차순 정렬
// int형 배열로 변경 후 반환
return Arrays.stream(result).mapToInt(Integer::intValue).toArray();
}
TreeSet 활용
TreeSet<Integer> set = new TreeSet<>(Collections.reverseOrder());
for (int num : arr) {
set.add(num);
}
int[] arr = new int[set.size()];
int i = 0;
for (int num : set) {
arr[i++] = num;
}
HashSet 활용
class Solution {
public static int[] solution(int[] numbers) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < numbers.length - 1; i++){
for(int j = 0; j < numbers.length - 1; j++){
set.add(numbers[i] + number[j]);
}
return set.stream().sorted().mapToInt(Integer::intValue).toArray();
}
}
새로운 클래스 생성하고 정렬해야 하는 케이스
public class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
List<Pair> list = new ArrayList<>();
list.add(new Pair(2, 5));
list.add(new Pair(1, 9));
list.add(new Pair(3, 4));
// x 기준 오름차순 정렬
list.sort(Comparator.comparingInt(p -> p.x));
// y 기준 내림차순 정렬
list.sort((a,b) -> Integer.compare(b.y, a.y)
// x 기준 정렬 후, y 기준 정렬
list.sort(Comparator.compairingInt((Pair p) -> p.x)
.thenComparingInt(p -> p.y));
다시 풀어야 할 문제
https://school.programmers.co.kr/learn/courses/30/lessons/42889
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr