포스트

뒤에서 5등까지

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

문제

  • 문제 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Solution {
    public static List<Integer> solution(int[] num_list) {
        List<Integer> resultList = new ArrayList<>();
        // 정렬
        Arrays.sort(num_list);
        // 정렬된 배열에서 가장 작은 5개의 수를 리스트에 추가
        for (int i = 0; i < Math.min(5, num_list.length); i++) {
            resultList.add(num_list[i]);
        }
        return resultList;
    }

    public static void main(String[] args) {
        int[] num_list = {12, 4, 15, 46, 38, 1, 14};
        List<Integer> result = solution(num_list);
        System.out.println(result); // 출력: [1, 4, 12, 14, 15]
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.Arrays;

class Solution {
    public int[] solution(int[] num_list) {
				int[] result = new int[5];
        Arrays.sort(num_list);

        for (int i = 0; i < 5; i++) {
            result[i] = num_list[i];
        }

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

class Solution {
    public List<Integer> solution(int[] num_list) { // 반환타입이 리스트일 경우
        List<Integer> result = new ArrayList<>();
        Arrays.sort(num_list);

        for (int i = 0; i < 5; i++) { // 가장 작은 5개의 수를 오름차순으로 추출
            result.add(num_list[i]);
        }

        return result;
    }
}


  • Math.min(a, b) 함수
    • 주어진 두 개의 숫자 ab 중에서 작은 값을 반환하는 메서드이다.
    • 예를 들어, Math.min(5, 3)는 3을 반환하고, Math.min(10, 10)은 10을 반환한다. 이 메서드는 두 인자 중 작은 값을 찾는데 사용된다.
    • 위의 코드에서는 Math.min(5, num_list.length)을 사용하여 num_list 배열의 길이와 5 중에서 작은 값을 선택하여 반복문의 루프 횟수를 결정한다. 이렇게 함으로써 배열의 길이가 5보다 작을 경우 배열의 모든 요소를 반복하지 않고도 가장 작은 5개의 요소만을 처리할 수 있다.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.