【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| ∣x−y∣放回陣列,否則取出消失。重複此操作。問陣列最後剩下哪個數(如果不剩則返回 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】1690. Stone Game VIILeetCodeGAM
- [LeetCode] 528. Random Pick with WeightLeetCoderandom
- [leetcode]length-of-last-wordLeetCodeAST
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- Weight for weight JavaScript趣題:減肥俱樂部JavaScript
- The Mark by Stone and Flower Made
- HDU 1729 Stone GameGAM
- Weight&Biases教程
- 7.121 LASTAST
- Last danceAST
- E:last-child與E:last-of-type區別AST
- 1046. 最後一塊石頭的重量
- Android之深刻理解layout_weightAndroid
- 7.122 LAST_DAYAST
- Last digit of a huge numberASTGit
- 織夢dedecms自定義文章排序weight用法排序
- Linux基礎命令—lastLinuxAST
- Linux基礎命令---lastLinuxAST
- CSS E:last-childCSSAST
- CSS E:last-of-typeCSSAST
- Traceback (most recent call last):AST
- 天國的《The Last Night》AST
- LightOj1296Again Stone Game(手推SG函式)AIGAM函式
- The last major melee archetype includes the sneakyAST
- Stone Temple:Google智慧助手仍然是最聰明的Go
- CSS E:nth-last-of-type(n)CSSAST
- CSS E:nth-last-child(n)CSSAST
- Oracle的LAST_DAY函式OracleAST函式
- mysql中last_insert_id()用法MySqlAST
- PG: Estimate last modified or read time of a tableAST
- 【每日一題】力扣1046.最後一塊石頭的重量每日一題力扣
- [20190728]分析函式LAST_VALUE.txt函式AST
- Last_IO_Error: Got fatal error 1236ASTErrorGo
- WARNING: Heavy swapping observed on system in last 5 minsAPPAST
- Expires, Last-Modified, Etag快取機制AST快取
- perl next, last, regular expression 實用場景ASTExpress
- 【藍橋記】:LAST DANCE | 最後一舞AST