Advertisement
K_S_

Untitled

Nov 28th, 2019
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. // Runtime: 79 ms, faster than 84.61% of Java online submissions for Find Median from Data Stream.
  2. // Memory Usage: 66 MB, less than 55.93% of Java online submissions for Find Median from Data Stream.
  3.  
  4. class MedianFinder {
  5.  
  6.     /** initialize your data structure here. */
  7.     public MedianFinder() {
  8.        
  9.     }
  10.    
  11.     private List<Integer> nums = new ArrayList<>();
  12.     public void addNum(int num) {
  13.         int idx = Collections.binarySearch(nums, num);
  14.         int ip = idx;
  15.         if (idx < 0) {
  16.             ip = -idx - 1;
  17.         }
  18.         nums.add(ip, num);
  19.     }
  20.  
  21.     public double findMedian() {
  22.         int sizeIdx = nums.size()-1;
  23.         if (nums.size() % 2 == 0) {
  24.             return (nums.get(sizeIdx / 2) + nums.get(sizeIdx / 2 + 1)) / 2.;
  25.         } else {
  26.             return nums.get(sizeIdx / 2);
  27.         }
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement