Leetcode Weekly Contest 256(滑动窗口、排序、状态压缩、动态规划)

题目链接: Leetcode Weekly Contest 256

1、1984. Minimum Difference Between Highest and Lowest of K Scores

难度:Easy

思路:

对数组从小到大排序,然后用长度为k的滑动窗口进行求解。

代码:

class Solution {
    public int minimumDifference(int[] nums, int k) {
        if(k==1){
            return 0;
        }
        Arrays.sort(nums);
        int res=Integer.MAX_VALUE;
        for(int i=0;i+k-1<nums.length;i++){
            int j=i+k-1;
            if(nums[j]-nums[i]<res){
                res=nums[j]-nums[i];
            }
        }
        return res;
    }
}

2、1985. Find the Kth Largest Integer in the Array

难度:Medium

思路:

对字符串数组进行排序即可。

class Solution {
    public String kthLargestNumber(String[] nums, int k) {
        Arrays.sort(nums,(a,b)->a.length()!=b.length()?a.length()-b.length():a.compareTo(b));
        return nums[nums.length-k];
    }
}

3、1986. Minimum Number of Work Sessions to Finish the Tasks

难度:Medium

思路:

参考高赞回答,状态压缩+DP。

代码

class Solution {
    public int minimizeTheDifference(int[][] mat, int target) {
        int m=mat.length;
        int n=mat[0].length;
        int minSum=0;//每行最小值之和
        for(int i=0;i<m;i++){
            int min=Integer.MAX_VALUE;
            for(int j=0;j<n;j++){
                if(mat[i][j]<min){
                    min=mat[i][j];
                }
            }
            minSum+=min;
        }
        if(minSum>=target){
            return minSum-target;
        }
        Set<Integer> prev=new HashSet<>();
        prev.add(0);
        for(int i=0;i<m;i++){
            Set<Integer> cur=new HashSet<>();
            for(int j=0;j<n;j++){
                for(int v:prev){
                    if(v+mat[i][j]-target<=target-minSum){
                        cur.add(v+mat[i][j]);
                    }
                }
            }
            prev=cur;
        }
        int res=Integer.MAX_VALUE;
        for(int v:prev){
            if(Math.abs(v-target)<res){
                res=Math.abs(v-target);
            }
        }
        return res;
    }
}

4、1987. Number of Unique Good Subsequences

难度:Hard

思路

参考高赞回答,与leetcode 940类似。

代码

class Solution {
    public int numberOfUniqueGoodSubsequences(String binary) {
        int mod=1000_000_007,res=0,ends0=0,ends1=0;
        int has0=0;
        for(char c:binary.toCharArray()){
            if(c=='0'){
                ends0=ends0+ends1;//以0结尾的子序列数量
                ends0%=mod;
                has0=1;
            }
            else{
                ends1=ends0+ends1+1;
                //'1'可以单独作为一个子序列,所以+1
                ends1%=mod;
            }
        }
        return (ends0+ends1+has0)%mod;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值