[剑指offer]面试题第[41]题[Leetcode][第235题][JAVA][数据流中的中位数][优先队列][堆]
【問(wèn)題描述】[困難]
【解答思路】
1. 思路1
時(shí)間復(fù)雜度:O(logN) 空間復(fù)雜度:O(N)
import java.util.PriorityQueue;public class MedianFinder {/*** 當(dāng)前大頂堆和小頂堆的元素個(gè)數(shù)之和*/private int count;private PriorityQueue<Integer> maxheap;private PriorityQueue<Integer> minheap;/*** initialize your data structure here.*/public MedianFinder() {count = 0;//maxHeap = new PriorityQueue<>(Collections.reverseOrder());maxheap = new PriorityQueue<>((x, y) -> y - x);minheap = new PriorityQueue<>();}public void addNum(int num) {count += 1;maxheap.offer(num);minheap.add(maxheap.poll());// 如果兩個(gè)堆合起來(lái)的元素個(gè)數(shù)是奇數(shù),小頂堆要拿出堆頂元素給大頂堆if ((count & 1) != 0) {maxheap.add(minheap.poll());}/*//如果不平衡則調(diào)整 不用countif (minHeap.size() > maxHeap.size()) {maxHeap.offer(minHeap.poll());}*/}public double findMedian() {if ((count & 1) == 0) {// 如果兩個(gè)堆合起來(lái)的元素個(gè)數(shù)是偶數(shù),數(shù)據(jù)流的中位數(shù)就是各自堆頂元素的平均值return (double) (maxheap.peek() + minheap.peek()) / 2;} else {// 如果兩個(gè)堆合起來(lái)的元素個(gè)數(shù)是奇數(shù),數(shù)據(jù)流的中位數(shù)大頂堆的堆頂元素return (double) maxheap.peek();} //不用count public double findMedian() {if (maxHeap.size() == minHeap.size()) {return (maxHeap.peek() + minHeap.peek()) * 0.5;}return maxHeap.peek();}} }2. 思路2
復(fù)雜度
【總結(jié)】
1.最大堆/最小堆初始化
最小堆
PriorityQueue minheap = new PriorityQueue<>();
最大堆
PriorityQueue maxheap = new PriorityQueue<>((x, y) -> y - x);
PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder());
2.找規(guī)律 模擬過(guò)程 不可能是一蹴而就 而是多次失敗后才能找到的規(guī)律和轉(zhuǎn)移過(guò)程
轉(zhuǎn)載鏈接:https://leetcode-cn.com/problems/find-median-from-data-stream/solution/you-xian-dui-lie-python-dai-ma-java-dai-ma-by-liwe/
參考鏈接:https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/solution/you-xian-dui-lie-wu-fei-hua-jian-dan-yi-dong-by-je/
參考鏈接:https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/solution/mian-shi-ti-41-shu-ju-liu-zhong-de-zhong-wei-shu-y/
總結(jié)
以上是生活随笔為你收集整理的[剑指offer]面试题第[41]题[Leetcode][第235题][JAVA][数据流中的中位数][优先队列][堆]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 工业铝型材是怎样去生产的
- 下一篇: cisco数据中心理论小记-3