一、1046.最后一块石头的重量
题目链接:1046.最后一块石头的重量
题目描述:

题目解析:
- 题意就是让我们拿出提供的数组的最大两个值,大减小作差,将差值再放入数组,直到数组空了或者只有一个元素为止。
解题思路:
- 题目要求我们在一个乱序的数组中找最大两个值,我们首先想到数组排序,但是由于我们还需要将差值放入数组,我们放一次就需要排序一次。
- 使用优先级队列,大根堆,开销会小一些,我们只需要每次拿堆顶元素即可。
解题代码:
//时间复杂度 O(n)//空间复杂度 O(n)
class Solution {
public int lastStoneWeight(int[] stones) {
//创建大根堆
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
//入堆
for (int i = 0; i < stones.length; i++) queue.offer(stones[i]);
//执行逻辑
while (!queue.isEmpty() && queue.size() != 1) {
int y = queue.poll();
int x = queue.poll();
queue.offer(y - x);
}
//返回值
return queue.isEmpty() ? 0 : queue.poll();
}
}
二、703. 数据流中的第 K 大元素
题目链接:703. 数据流中的第 K 大元素




