代码(Python3) class Solution: def lastStoneWeight(self, stones: List[int]) -> int: # 由于 heapq 默认是最小堆,所以这里取相反数进行转换 heap: List[int] = [-num for num in stones] # 通过数组直接建立堆 heapq.heapify(heap) # 至少还有两个数字时,继续循环处理 while len(heap) > 1: # ...
链接:leetcode-cn.com/problem 提示 为了实现全局最小,首先从实现局部最小开始吧 本题关键字:贪心算法,优先队列 解析 思路 对于每一个stone, s,为了使相减结果最小,我们必然要寻找重量最接近s的另一个stone,且由于选大选小关系不方便判断,可以尝试从最大的s开始计算起(因为此时重量差距最小的即为第二大的...
classSolution{public:intlastStoneWeight(vector<int>& stones){ priority_queue<int> q;for(intstone : stones) q.push(stone);while(q.size() >1) {intfirst = q.top(); q.pop();intsecond = q.top(); q.pop();if(first > second) q.push(first - second); }returnq.empty() ?0: q.t...
最后判断队列是否为空,为空就返回0,不为空就返回队首的元素值。 publicintlastStoneWeight3(int[] stones){ PriorityQueue<Integer> pq =newPriorityQueue<>(Comparator.reverseOrder());for(intstone : stones) { pq.offer(stone); }while(pq.size() >1) {intnum=pq.poll() - pq.poll();if(num >0)...
classSolution{publicintlastStoneWeightII(int[]stones){intsum=0;for(intstone:stones)sum+=stone;int[]dp=newint[(sum>>>1)+1];for(intstone:stones)for(intj=(sum>>>1);j>stone-1;j--)dp[j]=Math.max(dp[j],dp[j-stone]+stone);returnsum-(dp[(sum>>>1)]<<1);}} ...
packageleetcodefunclastStoneWeightII(stones[]int)int{sum:=0for_,v:=rangestones{sum+=v}n,C,dp:=len(stones),sum/2,make([]int,sum/2+1)fori:=0;i<=C;i++{ifstones[0]<=i{dp[i]=stones[0]}else{dp[i]=0}}fori:=1;i<n;i++{forj:=C;j>=stones[i];j--{dp[j]=max(dp[...
class Solution { public int lastStoneWeight(int[] stones) { // Insert all the stones into a Max-Heap. PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder()); for (int stone: stones) {//contrcut heap will takes O(n) instead of O(nlogn) ...
pq.offer(pq.poll()-pq.poll());returnpq.poll(); } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. https://leetcode.com/problems/last-stone-weight/discuss/294956/JavaC%2B%2BPython-Priority-Queue 大神总是能一次次的使我下巴脱臼
1classSolution {2public:3intlastStoneWeight(vector<int>&stones) {45while(stones.size()>1)6{7sort(stones.begin(),stones.end());8if(stones[stones.size()-1]==stones[stones.size()-2])9{10stones.pop_back();stones.pop_back();11}12else13{14inttt = stones[stones.size()-1]-stones[...
classSolution{public:intlastStoneWeight(vector<int>&stones){if(stones.size()==1)returnstones[0];while(stones.size()>=2){heapsort(stones);// print(stones);intp,q;p=stones.back();stones.pop_back();q=stones.back();stones.pop_back();intdiff=p-q;if(diff)stones.push_back(diff);}if...