Space: O(n). AC Java: 1classSolution {2publicintlastStoneWeight(int[] stones) {3if(stones ==null|| stones.length == 0){4return0;5}67PriorityQueue<Integer> maxHeap =newPriorityQueue<>(Collections.reverseOrder());8for(intstone : stones){9maxHeap.add(stone);10}1112while(maxHeap.size(...
Time Complexity: O(n*sum). n = stones.length. sum is total weight of stones. Space: O(sum). AC Java: 1classSolution {2publicintlastStoneWeightII(int[] stones) {3if(stones ==null|| stones.length == 0){4return0;5}67intsum = 0;8boolean[] dp =newboolean[1501];9dp[0] =true...
链接:leetcode-cn.com/problem 提示 为了实现全局最小,首先从实现局部最小开始吧 本题关键字:贪心算法,优先队列 解析 思路 对于每一个stone, s,为了使相减结果最小,我们必然要寻找重量最接近s的另一个stone,且由于选大选小关系不方便判断,可以尝试从最大的s开始计算起(因为此时重量差距最小的即为第二大的...
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(...
Java: 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[...
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 大神总是能一次次的使我下巴脱臼
but can we lower all those prices? space time trade off, so…max/minheap, which will make remove and add in both O(logn) time and find in O(1) time. and the implement will be easy as hell: class Solution { public int lastStoneWeight(int[] stones) { ...
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); ...
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[...