Problem
The median of a list of numbers is essentially its middle element after sorting. The same number of elements occur after it as before. Given a list of numbers with an odd number of elements, find the median?
Example
The sorted array . The middle element and the median is .
Function Description
Complete the findMedian function in the editor below.
findMedian has the following parameter(s):
- int arr[n]: an unsorted array of integers
Returns
- int: the median of the array
Input Format
The first line contains the integer , the size of .
The second line contains space-separated integers
Constraints
- is odd
Sample Input 0
7
0 1 2 4 6 5 3
Sample Output 0
3
Explanation 0
The sorted . It's middle element is at .
Solution
public static int findMedian(List<Integer> arr) {
Collections.sort(arr); // 배열을 정렬
return arr.get(arr.size() / 2); // 가운데 숫자를 반환
}
1. Collections.sort(arr)
- Collections 클래스는 Java의 컬렉션 프레임워크에 포함되어 있으며, 다양한 유틸리티 메서드를 제공합니다. 이 클래스는 컬렉션을 다루기 위한 메서드를 정적(static)으로 제공하며, 배열, 리스트, 셋 등을 포함합니다.
- sort 메서드는 주어진 리스트를 오름차순으로 정렬하는 데 사용됩니다. 내부적으로 병합 정렬(Merge Sort) 알고리즘을 사용하여 안정성을 유지하면서 정렬을 수행합니다.
2. arr.size() / 2
- 리스트의 중간 인덱스를 계산합니다.
- 리스트의 크기가 홀수인 경우 정확히 중간 요소의 인덱스를 반환하며, 리스트의 크기가 짝수인 경우에도 중간 인덱스를 반환합니다 (이 경우 중간 인덱스는 항상 두 개의 요소 중 아래쪽 인덱스).
이 코드는 주어진 정수 리스트의 중위수를 효율적으로 계산하는 방법을 보여줍니다. Collections.sort 메서드를 사용하여 리스트를 정렬하고, 중간 인덱스를 통해 중위수를 쉽게 찾을 수 있습니다. Collections 클래스는 다양한 컬렉션 작업을 위한 유용한 메서드를 제공하므로, 리스트를 다루는 데 매우 유용합니다.
'코딩 테스트' 카테고리의 다른 글
[HackerRank] Diagonal Difference (0) | 2024.09.24 |
---|---|
[HackerRank] Lonely Integer (2) | 2024.09.23 |
[HackerRank] Plus Minus (0) | 2024.09.23 |
[HackerRank] Mini-Max Sum (3) | 2024.09.23 |
[HackerRank] Time Conversion (0) | 2024.09.23 |