goden1720

package
v0.0.0-...-b071cee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2023 License: GPL-3.0 Imports: 1 Imported by: 0

README

面试题 17.20.连续中值

1. 题目描述

随机产生数字并传递给一个方法。你能否完成这个方法,在每次产生新值时,寻找当前所有值的中间值(中位数)并保存。

中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。

例如,

[2,3,4] 的中位数是 3

[2,3] 的中位数是 (2 + 3) / 2 = 2.5

设计一个支持以下两种操作的数据结构:

  • void addNum(int num) - 从数据流中添加一个整数到数据结构中。
  • double findMedian() - 返回目前所有元素的中位数。 示例:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

标签 设计 双指针 数据流 排序 堆(优先队列)

2. 解题

用两个堆,一个大顶堆,一个小顶堆,大顶堆中存储较小的那部分数,小顶堆中存储较大的那部分数。则其中值为两个堆的堆顶元素和的平均值

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MaxHeap

type MaxHeap []int

func (*MaxHeap) Len

func (h *MaxHeap) Len() int

func (*MaxHeap) Less

func (h *MaxHeap) Less(i int, j int) bool

func (*MaxHeap) Pop

func (h *MaxHeap) Pop() (v interface{})

func (*MaxHeap) Push

func (h *MaxHeap) Push(x interface{})

func (*MaxHeap) Swap

func (h *MaxHeap) Swap(i int, j int)

type MedianFinder

type MedianFinder struct {
	// contains filtered or unexported fields
}

func Constructor

func Constructor() MedianFinder

* initialize your data structure here.

func (*MedianFinder) AddNum

func (this *MedianFinder) AddNum(num int)

func (*MedianFinder) FindMedian

func (this *MedianFinder) FindMedian() float64

type MinHeap

type MinHeap []int

func (*MinHeap) Len

func (h *MinHeap) Len() int

func (*MinHeap) Less

func (h *MinHeap) Less(i int, j int) bool

func (*MinHeap) Pop

func (h *MinHeap) Pop() (v interface{})

func (*MinHeap) Push

func (h *MinHeap) Push(x interface{})

func (*MinHeap) Swap

func (h *MinHeap) Swap(i int, j int)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL