I. Test instructions Description
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. The median is the mean of the middle value.
Examples:
[2,3,4]
, the median is3
[2,3]
, the median is(2 + 3) / 2 = 2.5
Design a data structure that supports the following and the operations:
void addnum (int num)-Add A integer number from the data stream to the data structure
Double Findmedian ()-Return The median of all elements so far.
In short, it is the implementation of a data structure that enables the insertion operation and obtains the median of a set of numbers.
Two. First, since this is a group of numbers, it is easy to think of using vectors for storage. Because the median of a set of numbers needs to be sorted first, it is thought that you should sort them at the same time as you insert them. In order to optimize the performance of the algorithm, we can use the binary insertion, the edge of the insertion edge sorting. The advantage of doing this is to keep this group of numbers at all times a well-ordered state, with the time Complexity O (1) for the median operation.
Because this problem is relatively simple, mainly using the two-point method of thought, so directly posted the code as follows:
classMedianfinder { Public: Vector<int>Nums; //Adds A number into the data structure. voidAddnum (intnum) { if(!nums.size ()) {nums.push_back (num); return; } intStart =0; intEnd = Nums.size ()-1; intMid = (start + end)/2; while(1) {Mid= (start + end)/2; if(num = =Nums[mid]) {Nums.insert (Nums.begin ()+mid, Num); Break; } Else if(Num >Nums[mid]) {Start= Mid +1; } Else{End= Mid-1; } if(Start >end) {Nums.insert (Nums.begin ()+start, num); Break; } } return; } //Returns The median of the current data stream DoubleFindmedian () {if(Nums.size ()%2) returnNums[nums.size ()/2]; Else return((Double) Nums[nums.size ()/2] + (Double) Nums[nums.size ()/2-1]) /2; }};
To find that you never think of it. int to double coercion type conversion ... But fortunately this error is relatively easy to see ...
Three. Summary
Read the other students blog found can also use a variety of self-sorting function of the STL structure, but I do not think t_t
Can only think of silly vector, really heart stuffed ...
Leetcode-find Median from Data Stream