LeetCode 1046. Last Stone Weight (最后一块石头的重量 )

题目标签:Greedy

  利用priority queue, 把石头重量都存入 pq, 每次取最大两个比较,存入差值,直到pq 只剩最后一个。

 

Java Solution:

Runtime:  1 ms, faster than 92.5% 

Memory Usage: 37.1 MB, less than 100%

完成日期:02/14/2020

关键点:priority queue

class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue <Integer> pq = new PriorityQueue<>((a, b) -> b - a);
        
        // add each stone weight into pq
        for(int s : stones) {
            pq.offer(s);
        }
        
        // each time get two max stones and add the difference back into pq
        while(pq.size() > 1) {
            pq.offer(pq.poll() - pq.poll());
        }
        
        return pq.poll();        
    }
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-02-15 03:03  Jimmy_Cheng  阅读(193)  评论(0编辑  收藏  举报