Leetcode - Best Time to Buy and Sell Stock IV
Leetcode - Serialize and Deserialize Binary Tree

Leetcode - Find Median from Data Stream

violet posted @ Jun 16, 2020 06:30:02 AM in 算法 with tags Algorithm Golang Heap , 439 阅读

https://leetcode.com/problems/find-median-from-data-stream/

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

 

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

 

type MinHeap []int

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *MinHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

type MaxHeap []int

func (h MaxHeap) Len() int           { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MaxHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *MaxHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

type MedianFinder struct {
    minHeap *MinHeap
    maxHeap *MaxHeap
    even bool
}


/** initialize your data structure here. */
func Constructor() MedianFinder {
    minHeap := &MinHeap{}
    maxHeap := &MaxHeap{}
    heap.Init(minHeap)
    heap.Init(maxHeap)
    return MedianFinder{
        minHeap: minHeap,
        maxHeap: maxHeap,
        even: true,
    }
}


func (this *MedianFinder) AddNum(num int)  {
    if this.even {
        heap.Push(this.maxHeap, num)
        heap.Push(this.minHeap, heap.Pop(this.maxHeap).(int))
    } else {
        heap.Push(this.minHeap, num)
        heap.Push(this.maxHeap, heap.Pop(this.minHeap).(int))
    }
    this.even = !this.even
}


func (this *MedianFinder) FindMedian() float64 {
    if this.even {
        return float64((*this.minHeap)[0] + (*this.maxHeap)[0])/2
    }
    return float64((*this.minHeap)[0])
}


/**
 * Your MedianFinder object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AddNum(num);
 * param_2 := obj.FindMedian();
 */

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter