1. 程式人生 > 實用技巧 >Leetcode (easy heap)

Leetcode (easy heap)

Leetcode (easy heap)

leetcode 簡單的堆題目總結

703 資料流中的第K大元素

class KthLargest{
  int size;
  private PriorityQueue<Integer> q;
  public KthLargest(int k,int[] nums){
    size = k;
    q = new PriorityQueue(k);
    for(int num:nums) add(num);
  }
  public int add(int val){
    if(q.size()<size) q.add(val);
    else if(q.peek()<val){
      q.poll();
      q.add(val);
    }
    return q.peek();
  }
}

1046 最後一塊石頭的重量

class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> (o2 - o1));
        for (int i = 0; i < stones.length; i++) {
            queue.offer(stones[i]);
        }
        while( queue.size() > 1 ) {
            int y = queue.poll();
            int x = queue.poll();
            int diff = y - x;
            if ( diff != 0 ) queue.offer(diff);
        }
        if ( queue.size() == 0 ) return 0;

        return queue.peek();
    }
}