1 public class MedianFinder 2 { 3 List<int> list = null; 4 int count = 0; 5 /** initialize your data structure here. */ 6 public MedianFinder() 7 { 8 this.list = new List<int>(); 9 } 10 11 public void AddNum(int num) 12 { 13 if (list.Count == 0) 14 { 15 list.Add(num); 16 } 17 else 18 { 19 if (num <= list[0]) 20 { 21 list.Insert(0, num); 22 } 23 else if (num >= list[list.Count - 1]) 24 { 25 list.Add(num); 26 } 27 else 28 { 29 for (int i = 0; i < list.Count; i++) 30 { 31 if (num >= list[i] && num <= list[i + 1]) 32 { 33 list.Insert(i + 1, num); 34 break; 35 } 36 } 37 } 38 } 39 count++; 40 } 41 42 public double FindMedian() 43 { 44 var mid = count / 2; 45 var re = count % 2; 46 if (re == 0) 47 { 48 var a = mid - 1; 49 var b = mid; 50 return Convert.ToDouble(list[a] + list[b]) / 2; 51 } 52 else 53 { 54 return Convert.ToDouble(list[mid]); 55 } 56 } 57 }