题目链接: 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;
}
}