https://leetcode.com/problems/find-median-from-data-stream/description/
Find Median from Data Stream - LeetCode
Can you solve this real interview question? Find Median from Data Stream - The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For exam
leetcode.com
주어진 클래스의 메서드를 완성시키는 문제이다. 이 때 입력된 숫자 값들의 중간 값, 짝수개 일 경우 중간 값 두 가지를 더한 후 나눈 값을 리턴시켜야 하는 메서드가 존재한다. 일반적인 List, LinkedList를 이용한 후 size 값으로 인덱스를 찾을 경우 시간 초과에 걸리게 된다.
문제를 해결하기 위해서 정렬에 효율적인 PriorityQueue를 이용하고, 중간 값을 찾기 편하게 하기 위하여 두 구간으로 나누었다. left 구간은 right 값보다 작은 값들로 peek 할 경우 중간 값, 짝수 사이즈일 때는 작은 중간 값을 확인할 수 있다. right 구간은 peek 할 경우 짝수 사이즈일 때 큰 중간 값을 확인할 수 있다. 이를 위해서 left PriorityQueue는 내림차순으로 Comperator를 설정해주어야 한다.
addNum 함수는 값이 들어오는 함수이다. 기본적으로 left의 조건을 확인하고 추가하고, 아닐 경우 right에 추가한다. 하지만 left에만 값이 쌓일 수 있는 경우의 수가 있으므로 사이즈를 비교해서 바로 left,right 균형을 맞춰 주었다.
addNum 함수와 PriorityQueue 두 구간으로 나누기를 완성했으면 중간 값을 구하는 메서드는 간단해진다. 홀 수 사이즈는 left에서 확인 가능하고 짝 수 사이즈는 left와 right에서 확인 가능하다. 단 값이 비어있는 경우 peek() 메서드에서 NullPointerException 이 발생할 수 있으므로 예외 값을 별도로 분기처리해주었다.
import java.util.*;
class MedianFinder {
PriorityQueue<Integer> left;
PriorityQueue<Integer> right;
public MedianFinder() {
left = new PriorityQueue<>((a,b) -> Integer.compare(b, a));
right = new PriorityQueue<>();
}
public void addNum(int num) {
if(left.isEmpty()){
left.add(num);
}else if(left.peek() > num){
left.add(num);
}else{
right.add(num);
}
while(right.size() > left.size()){
left.add(right.poll());
}
while(left.size() > right.size() + 1){
right.add(left.poll());
}
}
public double findMedian() {
double median = 0;
int size = left.size() + right.size();
if(size == 0){
return median;
}else if(size % 2 == 0){
median = (double)(left.peek() + right.peek())/2;
}else{
median = left.peek();
}
return median;
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/'Algolithm-Leetcode > Heaps & Priority Queue' 카테고리의 다른 글
| Task Scheduler (0) | 2026.08.16 |
|---|---|
| K Closest Points to Origin (0) | 2026.08.10 |
| Kth Largest Element in an Array (0) | 2026.07.31 |