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))
privateint 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; }
privateintbinaryIndex(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; }
publicstaticvoidmain(String[] args){ int[] array = newint[]{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()); } }