The median of the data flow in the offer to prove safety - cattle off network

topic

How to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values ​​after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values ​​of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read.

answer

This question can be used to do a binary search insertion position, because it is in the form of a data stream, just make sure that I ordered last insert a result of the operation, then use binary search insertion position, every sort of time complexity are O ( log (N))

AC Code

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
65
import java.util.ArrayList;





public class {

private int size = 0;
private ArrayList<Integer> source = new ArrayList<>();

public void (Integer NUM) { IF (size == 0 || NUM <source.get ( 0 )) { source.add ( 0 , NUM); } the else IF (NUM> source.get (size - . 1 )) { source.add (NUM); } the else {< large column of bovine guest net - the median of the data stream in the offer prove safety / span> Integer [] Array = new new Integer [source.size ()]; source.toArray (Array); int index = binaryIndex (Array, NUM); source.add (index, NUM); } size ++;




 






}

public Double GetMedian() {
if (size % 2 != 0) {
return Double.valueOf(source.get(size / 2));
}
int a = source.get(size / 2);
int b = source.get(size / 2 - 1);
return (a + b) / 2.0;
}

private int binaryIndex(Integer[] array, int key) {
int index = 0;
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = (right + left) / 2;
if (array[mid] == key) {
return mid;
}
if (array[mid] > key && array[mid - 1] < key) {
index = mid;
}
if (array[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return index;
}

public static void main(String[] args) {
int[] array = new int[]{2, 1, 4, 3, 6, 5, 8, 7, 10, 9};
Solution s = new Solution();
for (int i = 0; i < array.length; i ++) {
s.Insert(array[i]);
System.out.println(s.GetMedian());
}
}

}

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/12000182.html