1046. 最后一块石头的重量

优先队列

import java.util.Collections;
import java.util.PriorityQueue;

class Solution {
    public int lastStoneWeight(int[] stones) {

        /**
         * 使用优先队列创建最大堆
         * Collections.reverseOrder()比较器可以反转默认的最小堆
         */
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

        for (int i = 0; i < stones.length; i++) {
            pq.add(stones[i]);
        }

        while (pq.size() > 1){

            int y = pq.poll();
            int x = pq.poll();

            if (x != y) {
                pq.add(y - x);
            }
        }
        
        return pq.size() == 1 ? pq.poll() : 0;
    }
}

/**
 * 时间复杂度 O(nlogn)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/last-stone-weight/

posted @ 2021-11-01 16:55  振袖秋枫问红叶  阅读(30)  评论(0)    收藏  举报