Leetcode刷题笔记—heap (3)

LC 347 Top K Frequent Elements
LC 215 Kth Largest Element in an Array
LC 23 Merge k Sorted Lists

 23. Merge k Sorted Lists

1049. Last Stone Weight II

class Solution {
    public int lastStoneWeightII(int[] stones) {
        // S = S1 + S2, diff = S1 - S2, diff needs to be minimal, thus S - 2S2 will be minimal
        int S = 0, s2 = 0;
        for(int stone : stones) {
            S += stone;
        }
        int len = stones.length;
        boolean[][] dp = new boolean[S/2 + 1][len + 1];  // dp[s][i]: use stones from 0~i to construct sum s, if can construct then true else false
        for(int i = 0; i <= len; i++) {
            dp[0][i] = true;
        }
        for(int i = 1; i <= len; i++) {
            for(int sum = 1; sum <= S/2; sum++){
               int cur = stones[i - 1];
               if (sum >= cur) {
                   dp[sum][i] = dp[sum - cur][i - 1] || dp[sum][i - 1];           
               } else {
                   dp[sum][i] = dp[sum][i - 1];
               }
               if(dp[sum][i]) {
                   s2 = Math.max(sum, s2);
               }
               
            }
        }
        return S - 2 * s2;
    }
}

1046. Last Stone Weight

class Solution {
    public int lastStoneWeight(int[] stones) {
       PriorityQueue<Integer> heap = new PriorityQueue(Collections.reverseOrder());
       for(int each : stones)
       heap.add(each);
       while(heap.size() > 1) {
           int top1 = heap.poll();
           int top2 = heap.poll();
           int diff = Math.abs(top1 - top2);
           if(diff != 0) {
               heap.add(diff);
           }
       }
       if(heap.size() != 0) {
           return heap.poll();
       } else {
           return 0;
       }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值