【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]length-of-last-wordLeetCodeAST
- 【leetcode】length of last word (easy)LeetCodeAST
- Leetcode-Length of Last WordLeetCodeAST
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Weight for weight JavaScript趣題:減肥俱樂部JavaScript
- HDU 1729 Stone GameGAM
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- 【LeetCode從零單排】No58.Length of Last WordLeetCodeAST
- Weight&Biases教程
- ACM Same binary weightACM
- css font-weight原理CSS
- HDU1729 Stone Game (SG函式)GAM函式
- jQuery last()jQueryAST
- Last WinnerAST
- Last danceAST
- 7.121 LASTAST
- Who is the Last Change?AST
- E:last-child與E:last-of-type區別AST
- How to fix Rosetta stone error 2123 -- "This was an error in the application"ROSErrorAPP
- jQuery :last-of-typejQueryAST
- jQuery :last-childjQueryAST
- linux命令:lastLinuxAST
- 【每日一題】力扣1046.最後一塊石頭的重量每日一題力扣
- Stone Temple:Google智慧助手仍然是最聰明的Go
- 織夢dedecms自定義文章排序weight用法排序
- Android之深刻理解layout_weightAndroid
- Last digit of a huge numberASTGit
- CSS E:last-childCSSAST
- CSS E:last-of-typeCSSAST
- jQuery :nth-last-of-type()jQueryAST
- jQuery :nth-last-child()jQueryAST
- jQuery :last選擇器jQueryAST
- Length of Last Word leetocde javaASTJava
- 複用- build for last (轉)UIAST
- 7.122 LAST_DAYAST