포스트

뒤에서 5등 위로

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

문제

  • 문제 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Arrays;

class Solution {
    public int[] solution(int[] num_list) {
        // 배열을 복사하여 정렬 - 원본 배열을 직접 정렬하면 원본 배열의 순서가 변경되므로, 원본 배열의 순서를 유지하면서 정렬된 배열을 얻고자 할 때 배열을 복사한 후 정렬한다.
        int[] sortedArr = Arrays.copyOf(num_list, num_list.length);
        Arrays.sort(sortedArr); // 배열을 오름차순으로 정렬

        int[] result = new int[num_list.length - 5]; // 결과 배열의 크기는 num_list.length - 5

        // 가장 작은 5개의 수를 제외한 수를 결과 배열에 담음
        for (int i = 5; i < num_list.length; i++) {
            result[i - 5] = sortedArr[i];
        }

        return result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Arrays;

class Solution {
    public int[] solution(int[] num_list) {
        // 원본 배열을 정렬
        Arrays.sort(num_list); 

        int[] result = new int[num_list.length - 5]; // 결과 배열의 크기는 num_list.length - 5

        // 가장 작은 5개의 수를 제외한 수를 결과 배열에 담음
        for (int i = 5; i < num_list.length; i++) {
            result[i - 5] = num_list[i];
        }

        return result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.*;

class Solution { 
    public List<Integer> solution(List<Integer> num_list) { 
        Collections.sort(num_list); // 리스트를 오름차순으로 정렬

        List<Integer> result = new ArrayList<>();

        for (int i = 5; i < num_list.size(); i++) {
            result.add(num_list.get(i));
        }

        return result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public static List<Integer> solution(int[] num_list) {
        // 정수 배열을 리스트로 변환
        List<Integer> numList = new ArrayList<>();
        for (int num : num_list) {
            numList.add(num);
        }
        
        // 리스트를 오름차순으로 정렬
        numList.sort(null);
        
        // 가장 작은 5개의 수를 제외한 수들을 담을 리스트 생성
        List<Integer> resultList = new ArrayList<>(numList.subList(5, numList.size()));
        
        // 결과 반환
        return resultList;
    }

    public static void main(String[] args) {
        int[] num_list = {12, 4, 15, 46, 38, 1, 14, 56, 32, 10};
        List<Integer> result = solution(num_list);
        
        // 결과 출력
        System.out.println(result); // 출력: [15, 32, 38, 46, 56]
    }
}


  • ArrayList 생성자는 java.util.Arrays.ArrayList의 상위 클래스인 Collection type도 받는다.

    문제


  • subList() 메서드
    • 리스트의 일부분을 추출하여 새로운 리스트로 반환하는 메서드이다. 이 메서드는 원본 리스트의 일부분에 대한 뷰를 생성하므로, 반환된 리스트를 변경하면 원본 리스트도 변경된다.

      1
      
        List<E> subList(int fromIndex, int toIndex)
      
      • fromIndex는 포함할 첫 번째 요소의 인덱스이고, toIndex는 포함하지 않을 마지막 요소의 다음 인덱스이다. 즉, fromIndex 이상부터 toIndex 미만까지의 요소를 추출하여 새로운 리스트를 반환한다.
      • 예를 들어, 리스트 list[1, 2, 3, 4, 5]일 때, list.subList(1, 4)를 호출하면 인덱스 1부터 3까지의 요소 [2, 3, 4]를 포함하는 새로운 리스트를 반환한다.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.