第215场周赛 京东&力扣联合主办
5601. 设计有序流
class OrderedStream {
private String []nums;
private int ptr=1;
public OrderedStream(int n) {
nums=new String [n+2];
}
public List<String> insert(int id, String value) {
List<String> res=new ArrayList<>();
nums[id]=value;
if(id==ptr){
while(nums[ptr]!=null){
res.add(nums[ptr]);
ptr++;
}
}
return res;
}
}
5603. 确定两个字符串是否接近
1、字母种类相同
2、字母频率数组相同
class Solution {
public boolean closeStrings(String word1, String word2) {
int len1=word1.length();
int len2=word2.length();
if(len1!=len2){
return false;
}
int []c1=new int [26];
int []c2=new int [26];
for(int i=0;i<len1;i++){
c1[word1.charAt(i)-'a']++;
c2[word2.charAt(i)-'a']++;
}
for(int i=0;i<26;i++){
if((c1[i]==0)!=(c2[i]==0)){
return false;
}
}
Arrays.sort(c1);
Arrays.sort(c2);
for(int i=0;i<26;i++){
if(c1[i]!=c2[i]){
return false;
}
}
return true;
}
}
5602. 将 x 减到 0 的最小操作数
class Solution {
public int minOperations(int[] nums, int x) {
//找到需要减少的最小的个数,但是最后留下的一定是一个完整的子序列,则求解最长的子序列,使用双指针思想:
int left=0,right=0;
int sum=0;
for(int num:nums){
sum+=num;
}
sum-=x;
int temp=nums[0];
int ans=-1;
while(left<=right&&right<=nums.length-1){
while(temp>sum&&left<=right){
temp-=nums[left++];
}
if(temp==sum){
ans=Math.max(ans,right-left+1);
}
if(right==nums.length-1){
break;
}
temp+=nums[++right];
}
return ans==-1?-1:nums.length-ans;
}
}
5604. 最大化网格幸福感
方法一:状态压缩
class Solution {
private int statemax = 1, mod = 0, R = 0, C = 0;
private int[][][][][] dp;
public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) {
R = m;
C = n;
for(int i = 0; i < n; i ++) statemax *= 3;
mod = statemax / 3;
dp = new int[m][n][introvertsCount + 1][extrovertsCount + 1][statemax];
return dfs(0, 0, introvertsCount, extrovertsCount, 0);
}
private int dfs(int x, int y, int in, int ex, int last){
if(x == R) return 0;
if(y == C) return dfs(x + 1, 0, in, ex, last); // 有到达边界,直接看下一行
if(dp[x][y][in][ex][last] != 0) return dp[x][y][in][ex][last];
// 不安排
int res = dfs(x, y + 1, in, ex, last % mod * 3);
// 安排内向
if(in != 0) {
int t1 = 120, up = last / mod, left = last % 3;
if (x - 1 >= 0 && up != 0) {
t1 -= 30;
t1 += up == 1 ? -30 : 20;
}
if (y - 1 >= 0 && left != 0) {
t1 -= 30;
t1 += left == 1 ? -30 : 20;
}
res = Math.max(res, t1 + dfs(x, y + 1, in - 1, ex, last % mod * 3 + 1));
}
// 安排外向
if(ex != 0) {
int t2 = 40, up = last / mod, left = last % 3;;
if (x - 1 >= 0 && up != 0) {
t2 += 20;
t2 += up == 1 ? -30 : 20;
}
if (y - 1 >= 0 && left != 0) {
t2 += 20;
t2 += left == 1 ? -30 : 20;
}
res = Math.max(res, t2 + dfs(x, y + 1, in, ex - 1, last % mod * 3 + 2));
}
return dp[x][y][in][ex][last] = res;
}
}