题目链接: Leetcode Weekly Contest 242
写在前面:
本次周赛做出了第一题。
1、1869. Longer Contiguous Segments of Ones than Zeros
难度:Easy
题目大意:
详见题意。
思路:
模拟即可,统计字符串中连续0和连续1的最长长度,然后比较即可。
代码
class Solution {
public boolean checkZeroOnes(String s) {
char[] arr=s.toCharArray();
int len0=0,len1=0;
int maxLen0=0,maxLen1=0;
for(int i=0;i<arr.length;i++){
if(arr[i]=='1'){
len1++;
maxLen0=Math.max(maxLen0,len0);
len0=0;
}
else{
maxLen1=Math.max(maxLen1,len1);
len1=0;
len0++;
}
}
maxLen0=Math.max(maxLen0,len0);//最后一位,如111000
maxLen1=Math.max(maxLen1,len1);
if(maxLen1>maxLen0){
return true;
}
else{
return false;
}
}
}
2、1870. Minimum Speed to Arrive on Time
难度:Medium
题目大意:
详见题目。
思路:
参考高赞回答。对所有可能的速度进行二分查找,寻找符合条件的最小速度值。
代码
class Solution {
public int minSpeedOnTime(int[] dist, double hour) {
int sum=0;
int n=dist.length;
int res=-1;
int min=(int)Math.floor(sum/hour);
int max=10000000;
while(min<max){
double time=0;
int mid=(min+max+1)/2;
for(int j=0;j<n-1;j++){
time+=Math.ceil((double)dist[j]/mid);
}
time+=(double)dist[n-1]/mid;
if(time<=hour){
res=mid;
max=mid-1;
}
else{
min=mid;
}
}
return res;
}
}
3、1871. Jump Game VII
难度:Medium
题目大意:
详见题目。
思路:
参考高赞回答。用前缀和和动态规划求解。
代码
class Solution {
//参考https://leetcode-cn.com/problems/jump-game-vii/solution/tiao-yue-you-xi-vii-by-leetcode-solution-rsyv/
public boolean canReach(String s, int minJump, int maxJump) {
char[] arr=s.toCharArray();
int n=arr.length;
int[] f=new int[n];
int[] pre=new int[n];
f[0]=1;
for(int i=0;i<minJump;i++){
pre[i]=1;
}
for(int i=minJump;i<n;i++){
int left=i-maxJump,right=i-minJump;
if(arr[i]=='0'){
int total=pre[right]-(left<=0?0:pre[left-1]);
f[i]=(total>0?1:0);
}
pre[i]=pre[i-1]+f[i];
}
return f[n-1]>0;
}
}
4、1872. Stone Game VIII
难度:Hard
题目大意:
详见题目。
思路
参考高赞回答, 通过动态规划求解。
代码
class Solution {
public int stoneGameVIII(int[] stones) {
//https://leetcode-cn.com/problems/stone-game-viii/solution/shi-zi-you-xi-viii-by-leetcode-solution-e8dx/
int n=stones.length;
int[] pre=new int[n];
pre[0]=stones[0];
for(int i=1;i<n;i++){
pre[i]=pre[i-1]+stones[i];
}
int[] dp=new int[n];
dp[n-1]=pre[n-1];
for(int i=n-2;i>=0;i--){
dp[i]=Math.max(dp[i+1],pre[i]-dp[i+1]);
}
return dp[1];//一次至少取两个石头
}
}