这也是Google面试题

股市上一个股票的价格从开市开始是不停的变化的,需要开发一个系统,给定一个股票,它能实时显示从开市到当前时间的这个股票的价格的中位数(中值)。

用双堆存储,一个大根堆,一个小根堆,则Inert为O(logn),Median为O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.*;

public class FindMedian {
    private static PriorityQueue<Integer> maxHeap, minHeap;

    FindMedian(int n) {
        Comparator<Integer> revCmp = new Comparator<Integer>() {
            @Override
            public int compare(Integer left, Integer right) {
                return right.compareTo(left);
            }
        };

        // Or you can use Collections' reverseOrder method as follows.
        // Comparator<Integer> revCmp = Collections.reverseOrder();
        maxHeap = new PriorityQueue<Integer>(n, revCmp);
        minHeap = new PriorityQueue<Integer>(n);
    }

    public void addNewNumber(int randomNumber) {
        if (maxHeap.size() == minHeap.size()) {
            if ((minHeap.peek() != null) && randomNumber > minHeap.peek()) {
                maxHeap.offer(minHeap.poll());
                minHeap.offer(randomNumber);
            } else {
                maxHeap.offer(randomNumber);
            }
        }
        else {  // trick
            if(randomNumber < maxHeap.peek()) {
                minHeap.offer(maxHeap.poll());
                maxHeap.offer(randomNumber);
            }
            else {
                minHeap.offer(randomNumber);
            }
        }
    }

    public int getMedian() {
        if (maxHeap.isEmpty()) return minHeap.peek();
        else if (minHeap.isEmpty()) return maxHeap.peek();

        if (maxHeap.size() == minHeap.size()) {
            return (minHeap.peek() + maxHeap.peek()) / 2;
        } else if (maxHeap.size() > minHeap.size()) {
            return maxHeap.peek();
        } else {
            return minHeap.peek();
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        FindMedian fm = new FindMedian(n);
        for (int i = 0; i < n; i++) {
            int num = in.nextInt();
            fm.addNewNumber(num);
        }

        System.out.println(fm.getMedian());
    }
}