algorithm/leetcode

Find Median from Data Stream [LeetCode]

hoonzii 2021. 7. 12. 19:55
반응형

중간값이란 중간 위치의 값이다. 평균이 아니고!!!

문제 풀이 정리

 

문제

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 example, for arr = [2,3,4], the median is 3.
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], [1], [2], [], [3], []]

Output [null, null, null, 1.5, null, 2.0]

Explanation

MedianFinder medianFinder = new MedianFinder();

medianFinder.addNum(1); // arr = [1]

medianFinder.addNum(2); // arr = [1, 2]

medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)

medianFinder.addNum(3); // arr[1, 2, 3]

medianFinder.findMedian(); // return 2.0

 

Constraints:

  • -10^5 <= num <= 10^5
  • There will be at least one element in the data structure before calling findMedian.
  • At most 5 * 10^4 calls will be made to addNum and findMedian.

 

Follow up:

  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?

코드

class MedianFinder:
    
    num_list = []
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.num_list = []

    def addNum(self, num: int) -> None:
        self.num_list.append(num)
        self.num_list = sorted(self.num_list) #삽입시 정렬이 필요
        
    def findMedian(self) -> float:
        list_len = len(self.num_list)
        if list_len % 2 == 0: # 리스트 요소 개수가 짝수일 경우 중간 두개의 평균을 반환
            return (self.num_list[list_len//2] + self.num_list[list_len//2-1]) / 2
        else: # 리스트 요소 개수가 홀수일 경우 중간 인덱스 값 반환
            return self.num_list[list_len//2]


# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()

 

문제 넋두리

분명 레벨 고를때 easy를 골랐는데 자꾸 틀리는 거다...

열번 정도 틀리고 문제 다시 읽고, 다시 열번 틀리고 문제 다시 읽고....반복이였다.

그러다 마지막으로 읽은 부분 덕분에 통과 했다. (애초에 처음부터 잘읽었으면 한번에 맞출 레벨이다...)

there is no middle value and the median is the mean of the two middle values. -> 짝수면 중간 두개의 값 평균을 반환해라...

 

저부분을 못보고 계속 평균 값 반환하면서 왜 안돼!!! 절규 했었다.

문제 풀때마다 느끼는 거지만 문제를 잘 읽자!

 

반응형