【Leetcode】1046. Last Stone Weight

题目地址:

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

给定一个数组,每次取出两个最大的数 x x x y y y,如果 x ≠ y x\ne y x=y,则变为 ∣ x − y ∣ |x-y| xy放回数组,否则取出消失。重复此操作。问数组最后剩下哪个数(如果不剩则返回 0 0 0)。

可以用最大堆。代码如下:

import java.util.PriorityQueue;

public class Solution {
     
    public int lastStoneWeight(int[] stones) {
     
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((x, y) -> -Integer.compare(x, y));
        for (int stone : stones) {
     
            maxHeap.offer(stone);
        }
        
        while (maxHeap.size() > 1) {
     
            int x = maxHeap.poll(), y = maxHeap.poll();
            if (x != y) {
     
                maxHeap.offer(Math.abs(x - y));
            }
        }
        
        return maxHeap.isEmpty() ? 0 : maxHeap.peek();
    }
}

时间复杂度 O ( n log ⁡ n ) O(n\log n) O(nlogn) n n n是数组长度,空间 O ( n ) O(n) O(n)

你可能感兴趣的:(#,树,分治与堆,leetcode,算法,java)