当前位置:网站首页>1046. 最后一块石头的重量
1046. 最后一块石头的重量
2022-07-21 05:15:00 【安吉_lh1029】
1、题目描述
2、题目解析
因为每一回合都要选出【最重的两块石头】,因此每次都需要排序,可以联想到使用现成能够自动排序的数据结构,因此 想到【堆】这个可以自动实现排序的数据结构。
将所有的石头放入到大顶堆中,然后依次取出最重的两块石头x和y,必有x ≥ y。如果x > y,则将新石头x - y放回到最大堆中;如果x = y,两块石头完全被粉碎,因此不会产生新的石头。
- 用【JAVA】实现,声明 【降序】 的大根堆是难点:
- PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a, b) -> b - a);
实现代码如下:
class Solution {
public int lastStoneWeight(int[] stones) {
//申明大根堆,避免每次都进行排序
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b)->b-a);
for(int stone : stones){
pq.offer(stone);
}
while(pq.size() > 1){
//由于pq之前已经对数组进行排序,每次拿最大的两个数,只存在 b<=a的可能
int a = pq.poll();
int b = pq.poll();
//b=a时,两个直接poll即可,当b<a时,需要再往堆中写入(b-a)这个数字
if(b < a){
pq.offer(a-b);
}
}
return pq.isEmpty() ? 0:pq.poll();
}
}
复杂度分析
时间复杂度:O(nlogn),其中 n 是石头数量。每次从队列中取出元素需要花费 O(logn) 的时间,最多共需要粉碎 n−1 次石头。
空间复杂度:O(n)。
边栏推荐
- Huawei liteos memory management source code and architecture analysis
- 概率论-假设检验
- What are the functions and application industries of testing equipment development?
- 04 unittest unit test framework
- . Net memory leakage causes and Solutions
- 「跑象科技」获得天使+融资,打造新一代实时数据基础平台
- 3级学业水平测试
- Should the theme of IDE be bright or dark? The ultimate answer is coming!
- 并发开篇——带你从0到1建立并发知识体系的基石
- 集合间的映射和集合的势
猜你喜欢
Do you still have certificates to participate in the open source community?
What are the characteristics and application fields of Bluetooth module in the Internet of things?
Application advantages of WiFi module in the Internet of things
datart 自定义插件,不改动源代码,让 BI 顺利完成又一次创新
Yolov4 (Darknet version) post processing: display confidence and save the contents of the detection box locally
In depth analysis of LinkedList source code
Task and Await: Consuming Awaitable Methods
Teach you how to use yolov4 training and testing data set on the server (nanny level)
04 cadre d'essai de l'unit é unitest
为什么不用定时任务实现关闭订单?
随机推荐
3级学业水平测试
深入剖析多重背包问题(上篇)
Heap - principle to application - heap sort, priority queue
Learn multithreading, process and development board together
西瓜书第二章笔记-评估方法
一起学习SCP NFS TFTP
Introduction to general process choreography engine
Super practical 12 SQL optimization schemes
地产巨头,数据一体化建设项目方案(拿走不谢)
Teach you how to use Charles to grab bags
994. 腐烂的橘子
What are the functions and application industries of testing equipment development?
Why not use scheduled tasks to close orders?
Huawei liteos memory management source code and architecture analysis
「跑象科技」获得天使+融资,打造新一代实时数据基础平台
谷歌chrome--xpathhelper安装
三类基于贪心思想的区间覆盖问题
Paoding solves the fiboracci sequence and knapsack problem - analyze the optimization process of the two problems in detail, and take you to understand dynamic programming from the most basic problem!
Summary of actual process and steps of interface test
Learn SCP NFS TFTP together