Exemplo n.º 1
0
  public static void main(String args[]) throws IOException {

    String text = "C:\\Users\\Roshan Rajan\\Desktop\\squaredance.txt";
    String gender = "";
    PriorityQueue<String> men = new PriorityQueue<String>();
    PriorityQueue<String> women = new PriorityQueue<String>();
    BufferedReader input = new BufferedReader(new FileReader(text));
    String line = null;
    while ((line = input.readLine()) != null) {
      gender = line.substring(0, 1);
      if (gender.equals("M")) men.add(line.substring(2));
      else women.add(line.substring(2));
    }
    input.close();

    while (!men.isEmpty() && !women.isEmpty()) {
      System.out.println("The couples are ");
      System.out.println(men.poll() + " is Dancing with " + women.poll());
    }
    if (men.isEmpty()) {
      System.out.println(women.size() + " girls are Waiting to Dance");
      System.out.println(women.peek() + " is the first one waiting");
    }
    if (women.isEmpty()) {
      System.out.println(men.size() + " guys are Waiting to Dance");
      System.out.println(men.peek() + " is the first one waiting");
    }
  }
Exemplo n.º 2
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue.
  *
  * @return the head of this queue
  * @throws InterruptedException {@inheritDoc}
  */
 public E take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) available.await();
       else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
Exemplo n.º 3
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         if (nanos <= 0) return null;
         if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos);
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             long timeLeft = available.awaitNanos(delay);
             nanos -= delay - timeLeft;
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
 public int[] maxSlidingWindow(int[] nums, int k) {
   if (nums.length == 0 || k == 0) {
     return new int[] {};
   }
   int[] result = new int[nums.length - k + 1];
   PriorityQueue<Integer> priorityQueue =
       new PriorityQueue<Integer>(
           k,
           new Comparator<Integer>() {
             @Override
             public int compare(Integer o1, Integer o2) {
               if (o1 < o2) {
                 return 1;
               } else if (o1 > o2) {
                 return -1;
               } else {
                 return 0;
               }
             }
           });
   Deque<Integer> deque = new LinkedList<Integer>();
   for (int i = 0; i < k; i++) {
     deque.addLast(nums[i]);
     priorityQueue.add(nums[i]);
   }
   for (int i = k; i < nums.length; i++) {
     result[i - k] = priorityQueue.peek();
     int first = deque.removeFirst();
     priorityQueue.remove(first);
     deque.addLast(nums[i]);
     priorityQueue.add(nums[i]);
   }
   result[result.length - 1] = priorityQueue.peek();
   return result;
 }
Exemplo n.º 5
0
 public double getMedian() {
   if (smallerElements.size() == largerElements.size()) {
     return (smallerElements.peek() + largerElements.peek()) / 2.0;
   } else {
     return largerElements.peek();
   }
 }
Exemplo n.º 6
0
  public void purge() {
    CacheEntry queueEntry = expirationQueue.peek();

    while ((queueEntry != null) && queueEntry.isExpired()) {
      super.remove(queueEntry.getKey());
      expirationQueue.remove();
      queueEntry = expirationQueue.peek();
    }
  }
Exemplo n.º 7
0
 public Integer findMedian() {
   if (min.size() < max.size()) {
     return max.peek();
   } else if (max.size() < min.size()) {
     return min.peek();
   } else {
     return ((max.peek() + min.peek()) / 2);
   }
 }
Exemplo n.º 8
0
 public static void update(float tpf) {
   if (heap.isEmpty() == false) {
     myTime += (long) (tpf * 1000);
     while (heap.isEmpty() == false && ((Timer) heap.peek()).time < myTime) {
       Timer t = (Timer) heap.peek();
       heap.remove();
       t.execute();
     }
   }
 }
Exemplo n.º 9
0
 public int minMeetingRooms(Interval[] intervals) {
   Arrays.sort(intervals, new IntervalComparator());
   PriorityQueue<Integer> roomQueue = new PriorityQueue<Integer>();
   int num = 0;
   for (int i = 0; i < intervals.length; i++) {
     if (roomQueue.isEmpty()) {
       num++;
       System.out.println(intervals[i].end);
       roomQueue.offer(intervals[i].end);
     } else {
       int minEnd = roomQueue.peek();
       System.out.println("minEnd: " + minEnd);
       if (intervals[i].start < minEnd) {
         System.out.println("new offering " + intervals[i].end);
         num++;
         roomQueue.offer(intervals[i].end);
       } else {
         System.out.println("substitude " + intervals[i].end);
         roomQueue.poll();
         roomQueue.offer(intervals[i].end);
       }
     }
   }
   return num;
 }
Exemplo n.º 10
0
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      String X;
      PriorityQueue<Integer> pq = new PriorityQueue<>();
      Stack<Integer> stack = new Stack<>();

      while ((X = in.next()) != null) {
        int x = Integer.valueOf(X);
        pq.add(x);
        int sz = pq.size();
        int median = 0;

        if (sz == 1) {
          median = pq.peek();
        } else {
          for (int i = 0; i <= sz / 2; i++) {
            stack.add(pq.poll());
            if ((i == (sz / 2) - 1 && sz % 2 == 0) || i == (sz / 2)) {
              median += stack.peek();
            }
          }
          if (sz % 2 == 0) median /= 2;
        }

        while (!stack.isEmpty()) pq.add(stack.pop());
        out.printLine(median);
      }
    }
Exemplo n.º 11
0
  private HeightEvent nextEvent() {
    EdgeCollision ec;

    for (; ; ) {
      ec = faceEvents.poll();
      if (ec == null) break;
      // valid if we haven't seen it, and it's height is "greater" than
      // the current skeleton height
      if (!skel.seen.contains(ec) && ec.loc.z - skel.height > -0.001) break;
    }

    HeightEvent he = miscEvents.peek();

    if (ec == null) {
      return miscEvents.poll(); // might be null!
    }
    if (he == null) {
      skel.seen.add(ec);
      return ec; // might be null!
    }

    if (he.getHeight() <= ec.getHeight()) {
      faceEvents.add(ec);
      return miscEvents.poll(); // return he
    } else {
      skel.seen.add(ec);
      return ec; // return ec
    }
  }
Exemplo n.º 12
0
  public void reduce(
      Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter)
      throws IOException {

    while (values.hasNext()) {
      String line = values.next().toString();
      String[] tokens = line.split(",");

      try {
        double latitude = (Double.parseDouble(tokens[2]));
        double longitude = (Double.parseDouble(tokens[3]));

        Tuple t = new Tuple(longitude, latitude, line);
        t.setDistance(fp);
        if (queue.size() < k) {
          queue.add(t);
        } else {
          if (t.distance < queue.peek().distance) {
            queue.add(t);
            queue.remove();
          }
        }

      } catch (Exception c) {

      }
    }

    while (!queue.isEmpty()) {
      output.collect(new Text("1"), new Text(queue.remove().tupleData));
    }
  }
Exemplo n.º 13
0
 private void assertMinimumsAreEqual(
     java.util.PriorityQueue<Integer> oldQueue, PriorityQueue<Integer> newQueue) {
   assertThat(oldQueue.isEmpty()).isEqualTo(newQueue.isEmpty());
   if (!newQueue.isEmpty()) {
     assertThat(oldQueue.peek()).isEqualTo(newQueue.head());
   }
 }
Exemplo n.º 14
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay > 0) {
           if (nanos <= 0) return null;
           if (delay > nanos) delay = nanos;
           long timeLeft = available.awaitNanos(delay);
           nanos -= delay - timeLeft;
         } else {
           E x = q.poll();
           assert x != null;
           if (q.size() != 0) available.signalAll();
           return x;
         }
       }
     }
   } finally {
     lock.unlock();
   }
 }
Exemplo n.º 15
0
  /** The sensor manager determines what all of the sensors are able to confirm. */
  @Override
  public Environment apply(Environment t) {

    /*
     * If we have any omniscient sensors, they will be the first sensor on
     * the list.
     */
    Sensor firstSensor = sensors.peek();
    if (firstSensor instanceof OmniscientSensor) {
      return firstSensor.apply(t);
    }

    /*
     * Otherwise, extract the different types of sensor
     */
    LinkedList<ProximitySensor> proximitySensors = new LinkedList<>();
    for (Sensor sensor : sensors) {
      if (sensor instanceof ProximitySensor) {
        proximitySensors.add((ProximitySensor) sensor);
      }
    }

    /*
     * If we have no other sensors, throw a problem
     */
    if (proximitySensors.size() == 0) {
      throw new RuntimeException("Sensor was not omniscient!");
    }

    return proximitySensors.getFirst().apply(t);
  }
  /**
   * Evaluates a query.
   *
   * @param queryTree A query tree that has been already transformed with
   *     StructuredRetrieval.transformQuery.
   * @param requested The number of documents to retrieve, at most.
   * @return
   * @throws java.lang.Exception
   */
  public ScoredDocument[] runQuery(Node queryTree, int requested) throws Exception {

    // my addition
    queryTree = this.transformQuery(queryTree);

    // System.out.println("runQuery: " + queryTree.toString());

    // construct the query iterators
    ScoreIterator iterator = (ScoreIterator) createIterator(queryTree);

    // now there should be an iterator at the root of this tree
    PriorityQueue<ScoredDocument> queue = new PriorityQueue<ScoredDocument>();

    while (!iterator.isDone()) {
      int document = iterator.nextCandidate();
      int length = index.getLength(document);
      double score = iterator.score(document, length);

      if (queue.size() <= requested || queue.peek().score < score) {
        ScoredDocument scoredDocument = new ScoredDocument(document, score);
        queue.add(scoredDocument);

        if (queue.size() > requested) {
          queue.poll();
        }
      }

      iterator.movePast(document);
    }

    return getArrayResults(queue);
  }
  protected List<InputSplit> combineSplits(
      PriorityQueue<LuceneIndexInputSplit> splits,
      long maxCombinedIndexSizePerSplit,
      long maxNumIndexesPerSplit) {

    // now take the one-split-per-index splits and combine them into multi-index-per-split splits
    List<InputSplit> combinedSplits = Lists.newLinkedList();
    LuceneIndexInputSplit currentSplit = splits.poll();
    while (currentSplit != null) {
      while (currentSplit.getLength() < maxCombinedIndexSizePerSplit) {
        LuceneIndexInputSplit nextSplit = splits.peek();
        if (nextSplit == null) {
          break;
        }
        if (currentSplit.getLength() + nextSplit.getLength() > maxCombinedIndexSizePerSplit) {
          break;
        }
        if (currentSplit.getIndexDirs().size() >= maxNumIndexesPerSplit) {
          break;
        }
        currentSplit.combine(nextSplit);
        splits.poll();
      }
      combinedSplits.add(currentSplit);
      currentSplit = splits.poll();
    }
    return combinedSplits;
  }
Exemplo n.º 18
0
  public HeightEvent poll() {
    currentCoHeighted = null; // now working at a new height

    HeightEvent next = nextEvent();

    if (next instanceof EdgeCollision) {
      List<EdgeCollision> coHeighted = new ArrayList<EdgeCollision>();
      EdgeCollision ec = (EdgeCollision) next;
      coHeighted.add(ec);

      double height = ec.getHeight();

      for (; ; ) {
        EdgeCollision higher = faceEvents.peek();
        if (higher == null) break;
        if (higher.getHeight() - height < 0.00001) // ephemeral random
        // constant #34 was
        // 0.00001
        {
          faceEvents.poll(); // same as higher

          if (skel.seen.contains(higher)) continue;

          height = higher.getHeight();
          skel.seen.add(higher);
          coHeighted.add(higher);
        } else break;
      }

      return currentCoHeighted = new HeightCollision(coHeighted);
    } else return next;
  }
Exemplo n.º 19
0
  @Override
  public CategoricalResults classify(DataPoint data) {
    CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());

    // Use a priority que so that we always pick the two lowest value class labels, makes indexing
    // into the oneVsOne array simple
    PriorityQueue<Integer> options = new PriorityQueue<Integer>(predicting.getNumOfCategories());
    for (int i = 0; i < cr.size(); i++) options.add(i);

    CategoricalResults subRes;
    int c1, c2;
    // We will now loop through and repeatedly pick two combinations, and eliminate the loser, until
    // there is one winer
    while (options.size() > 1) {
      c1 = options.poll();
      c2 = options.poll();

      subRes = oneVone[c1][c2 - c1 - 1].classify(data);

      if (subRes.mostLikely() == 0) // c1 wins, c2 no longer a candidate
      options.add(c1);
      else // c2 wins, c1 no onger a candidate
      options.add(c2);
    }

    cr.setProb(options.peek(), 1.0);

    return cr;
  }
Exemplo n.º 20
0
    /**
     * Adds {@code value} to this heap if it is larger than any of the current elements. Returns
     * {@code true} if {@code value} was added.
     */
    private boolean maybeAddInput(T value) {
      if (maximumSize == 0) {
        // Don't add anything.
        return false;
      }

      // If asQueue == null, then this is the first add after the latest call to the
      // constructor or asList().
      if (asQueue == null) {
        asQueue = new PriorityQueue<>(maximumSize, compareFn);
        for (T item : asList) {
          asQueue.add(item);
        }
        asList = null;
      }

      if (asQueue.size() < maximumSize) {
        asQueue.add(value);
        return true;
      } else if (compareFn.compare(value, asQueue.peek()) > 0) {
        asQueue.poll();
        asQueue.add(value);
        return true;
      } else {
        return false;
      }
    }
Exemplo n.º 21
0
  /**
   * Get top N elements
   *
   * @param vec the vec to extract the top elements from
   * @param N the number of elements to extract
   * @return the indices and the sorted top N elements
   */
  private static List<Double> getTopN(INDArray vec, int N) {
    ArrayComparator comparator = new ArrayComparator();
    PriorityQueue<Double[]> queue = new PriorityQueue<>(vec.rows(), comparator);

    for (int j = 0; j < vec.length(); j++) {
      final Double[] pair = new Double[] {vec.getDouble(j), (double) j};
      if (queue.size() < N) {
        queue.add(pair);
      } else {
        Double[] head = queue.peek();
        if (comparator.compare(pair, head) > 0) {
          queue.poll();
          queue.add(pair);
        }
      }
    }

    List<Double> lowToHighSimLst = new ArrayList<>();

    while (!queue.isEmpty()) {
      double ind = queue.poll()[1];
      lowToHighSimLst.add(ind);
    }
    return Lists.reverse(lowToHighSimLst);
  }
Exemplo n.º 22
0
 // Time: O(n*logk)
 // Space: O(k)
 // Use min heap to store current end time of each room.
 // If current interval start time is smaller than the minimum end time,
 // create a new room (add end time to the heap)
 // Else, update the minimum end time
 // Return the size of heap
 public int minMeetingRooms(Interval[] intervals) {
   if (intervals == null || intervals.length == 0) return 0;
   Arrays.sort(
       intervals,
       new Comparator<Interval>() {
         @Override
         public int compare(Interval i1, Interval i2) {
           return i1.start - i2.start;
         }
       });
   PriorityQueue<Integer> heap = new PriorityQueue<Integer>();
   for (Interval interval : intervals) {
     if (heap.size() == 0) {
       heap.offer(interval.end);
     } else {
       if (interval.start < heap.peek()) {
         heap.offer(interval.end);
       } else {
         heap.poll();
         heap.offer(interval.end);
       }
     }
   }
   return heap.size();
 }
Exemplo n.º 23
0
  public void run() {
    synchronized (this) {
      ConnectionState connState;

      while (!Thread.interrupted()) {

        try {

          while (mRetryQueue.isEmpty()) wait();

          connState = mRetryQueue.peek();

          if (!connState.connected) {
            synchronized (connState) {
              long diffTime = connState.nextRetry - System.currentTimeMillis();

              if (diffTime <= 0) {
                mRetryQueue.remove(connState);
                /**
                 * if (!mQuietMode) log.info("Attempting to re-establish " "connection to " +
                 * connState.serviceName + " at " + connState.addr);
                 */
                SendConnectRequest(connState);
              } else {
                wait(diffTime);
              }
            }
          } else mRetryQueue.remove(connState);

        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
Exemplo n.º 24
0
  @Override
  public synchronized List<T> getTopK() {
    Comparator<T> comparator =
        new Comparator<T>() {
          public int compare(T key1, T key2) {
            return Longs.compare(counts.get(key1), counts.get(key2));
          }
        };
    PriorityQueue<T> topK = new PriorityQueue<T>(k, comparator);

    for (Map.Entry<T, Long> entry : counts.entrySet()) {
      if (topK.size() < k) {
        topK.offer(entry.getKey());
      } else if (entry.getValue() > counts.get(topK.peek())) {
        topK.offer(entry.getKey());
        topK.poll();
      }
    }

    LinkedList<T> sortedTopK = new LinkedList<T>();

    while (!topK.isEmpty()) {
      sortedTopK.addFirst(topK.poll());
    }

    return sortedTopK;
  }
Exemplo n.º 25
0
  public T receive() {
    lock.lock();
    try {
      while (true) {
        DelayedMessage message = queue.peek();
        if (message == null && stopping) {
          return null;
        }
        if (message == null) {
          condition.await();
          continue;
        }

        long now = timeProvider.getCurrentTime();
        if (message.dispatchTime > now) {
          condition.awaitUntil(new Date(message.dispatchTime));
        } else {
          queue.poll();
          if (queue.isEmpty()) {
            condition.signalAll();
          }
          return message.message;
        }
      }
    } catch (InterruptedException e) {
      throw UncheckedException.throwAsUncheckedException(e);
    } finally {
      lock.unlock();
    }
  }
Exemplo n.º 26
0
  @Override
  public int next() {
    long start = System.currentTimeMillis();

    if (currentDocId == Constants.EOF) {
      return currentDocId;
    }
    while (queue.size() > 0 && queue.peek().getLeft() <= currentDocId) {
      IntPair pair = queue.remove();
      iteratorIsInQueue[pair.getRight()] = false;
    }
    currentDocId++;
    // Grab the next value from each iterator, if it's not in the queue
    for (int i = 0; i < docIdIterators.length; i++) {
      if (!iteratorIsInQueue[i]) {
        int nextDocId = docIdIterators[i].advance(currentDocId);
        if (nextDocId != Constants.EOF) {
          if (!(nextDocId <= maxDocId && nextDocId >= minDocId) && nextDocId >= currentDocId) {
            throw new RuntimeException(
                "next Doc : "
                    + nextDocId
                    + " should never crossing the range : [ "
                    + minDocId
                    + ", "
                    + maxDocId
                    + " ]");
          }
          queue.add(new IntPair(nextDocId, i));
        }
        iteratorIsInQueue[i] = true;
      }
    }

    if (queue.size() > 0) {
      currentDocId = queue.peek().getLeft();
    } else {
      currentDocId = Constants.EOF;
    }
    long end = System.currentTimeMillis();
    timeMeasure.addAndGet(end - start);
    // Remove this after tracing is added
    // if (currentDocId == Constants.EOF) {
    // LOGGER.debug("OR took:" + timeMeasure.get());
    // }

    return currentDocId;
  }
Exemplo n.º 27
0
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int cases = sc.nextInt(), guests, i, j, c;
    long a, b;
    PriorityQueue<Long> beginTimes;
    PriorityQueue<Long> endTimes;
    // for each case
    for (c = 0; c < cases; c++) {
      //
      guests = sc.nextInt();
      beginTimes = new PriorityQueue<Long>();
      endTimes = new PriorityQueue<Long>();

      for (i = 0; i < guests; i++) {
        a = sc.nextLong();
        b = sc.nextLong();

        beginTimes.add(a);
        endTimes.add(a + b);
      }

      int currentChairs = 0;
      long starting = 0;
      long ending = 0;
      int max = 0;
      long present = 0;
      boolean flag = true;

      while (!beginTimes.isEmpty() || !endTimes.isEmpty()) {

        if (!beginTimes.isEmpty() && beginTimes.peek() <= endTimes.peek()) {
          currentChairs++;
          if (currentChairs > max) max = currentChairs;
          present = beginTimes.poll();
          starting = present;
          ending = present;
        } else {
          currentChairs--;
          present = endTimes.poll();
          ending = present;
        }
      }

      System.out.println(max);
    }
  }
 private boolean canExecute(long time) {
   QueueEntry entry = entries.peek();
   if (entry == null) {
     return false;
   } else {
     return canExecute(entry, time);
   }
 }
Exemplo n.º 29
0
 void run() {
   Scanner sc = new Scanner(System.in);
   int N = sc.nextInt(), M = sc.nextInt();
   PriorityQueue<R> q = new PriorityQueue<R>();
   while (M-- != 0) q.add(new R(sc.nextInt(), sc.nextInt()));
   int res = 0, f = 0;
   while (!q.isEmpty() && f < N) {
     if (f + 1 < q.peek().s) break;
     int max = q.poll().t;
     while (!q.isEmpty() && q.peek().s <= f + 1) max = Math.max(max, q.poll().t);
     if (f < max) {
       res++;
       f = max;
     }
   }
   System.out.println(f == N ? res : "Impossible");
 }
Exemplo n.º 30
0
  /*skylineII
  * 		// First: split building into two edge and sort
  // Second: create a max-heap with first height 0, we offer height and poll height
  // Third: for every edge, - put in(new skyline), + remove it(old skyline), if current max height not the same as before we add in
  // init 0, max height so far, if change, skyline redraw		//
  * */
  public List<int[]> skylineII(List<Interval> intervals) {
    List<int[]> res = new ArrayList<int[]>();
    if (intervals == null || intervals.size() == 0) {
      return res;
    }
    // First: split building into two edge and sort
    List<int[]> height = new ArrayList<int[]>();
    for (Interval item : intervals) {
      height.add(new int[] {item.start, -item.height}); // start, -height
      height.add(new int[] {item.end, item.height}); // end, height
    }
    Collections.sort(
        height,
        new Comparator<int[]>() {
          public int compare(int[] a, int[] b) {
            if (a[0] != b[0]) return a[0] - b[0];
            return a[1] - b[1]; // start BEFORE end, height small BEFORE height large
            // BOTH START -10,-5=> -10->-5
            // BOTH END 10, 5=>5->10
          }
        });
    // Second: create a max-heap with first height 0, we offer height and poll height
    // 根据position从前到后扫描每一个edge
    // 将edge根据是入还是出来将当前height加入或者移除heap
    // 再得到当前最高点(max-heap)来决定是否加入最终结果。

    // 把所有的turning points 放在一起,根据coordination从小到大sort 。
    // 再用max-heap, 把所有的turning points扫一遍,遇到start turning point,
    // 把 volume放入max-heap.
    // 遇到end turning point,把对应的volume从max-heap中取出。
    // max-heap的max 值就是对应区间的最大volume
    // Input : [2,-10][3,-15][5,-12][7,15][9,10][12,12][15,-10][19,-8][20,10][24,8]
    // Result: [2 10],[3 15],[7 12],[12 0],[15 10],[20 8],[24, 0]
    // Event{true,0,200}, Event{false,10,200}
    // ==> Event{0,200}, Event{10,-200}
    // 按照time排序,time相同,is_in = false的优先
    // 然后你扫过去, is_in=true的你就加mem,is_in=false的你就-mem.每个事件点,
    // 你会加或减一次,每加或减一次后,就check是不是超过总的
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10, new pqComparator());
    // Avoid empty heap, still has ZERO value
    pq.offer(0);
    int prev = 0;
    // Third: for every edge, - put in(new skyline), + remove it(old skyline), if current max height
    // not the same as before we add in
    // init 0, max height so far, if change, skyline redraw
    for (int[] item : height) {
      // START, ADD
      if (item[1] < 0) pq.offer(-item[1]);
      // END, REMOVE
      else pq.remove(item[1]);
      int max = pq.peek();
      if (prev != max) {
        res.add(new int[] {item[0], max});
        prev = max;
      }
    }
    return res;
  }