1 5763. 哪种连续子字符串更长
class Solution {
public:
bool checkZeroOnes(string s) {
int cnt1 = 0, cnt0 = 0;
int res1 = 0, res0 = 0;
int n = s.size();
for(int i = 0; i < n; i++)
if(s[i] == '0')
{
cnt0++;
res0 = max(res0, cnt0);
cnt1 = 0;
}
else
{
cnt1++;
res1 = max(res1, cnt1);
cnt0 = 0;
}
return res1 > res0;
}
};
2 5764. 准时到达的列车最小时速
思路:二分+检查
class Solution {
public:
vector<int> d;
int n;
double h;
bool check(int sp)
{
double res = 0;
for(int i = 0; i < n - 1; i++)
{
if(d[i] % sp == 0)res += d[i] / sp;
else res += d[i] / sp + 1;
}
res += (double)d[n - 1] / sp;
//cout << sp << ' ' << res << endl;
return res <= h;
}
int minSpeedOnTime(vector<int>& dist, double hour) {
n = dist.size(), h = hour;
d = dist;
if(hour < n - 1)return -1;
int l = 1, r = INT_MAX - 1, mid;
while(l < r)
{
mid = l + r >> 1;
if(check(mid))r = mid;
else l = mid + 1;
}
return l;
}
};
3 5765. 跳跃游戏 VII
思路:二分
class Solution {
public:
bool canReach(string s, int minJump, int maxJump) {
int n = s.size();
if(s[n - 1] == '1')return false;
if(n == 1)return true;
vector<int>a;//存放能够跳到的下标
a.push_back(0);
for(int i = 1; i < n; i++)
{
if(s[i] == '1')continue;
int up = i - minJump, down = i - maxJump;
int l = 0, r = a.size() - 1, mid;
while(l < r)//二分查找a中第1个大于等于down的元素,该元素同时又是最可能小于等于up的元素,所以只用一次二分即可
{
mid = l + r >> 1;
if(a[mid] >= down)r = mid;
else l = mid + 1;
}
if(a[l] >= down && a[l] <= up)
a.push_back(i);
}
return a.back() == n - 1;
}
};
4 5766. 石子游戏 VIII
参考:LeetCode官方题解
PS:做题的时候题目没看清,误入模拟的歧途,没想动态规划。
思路:
- 状态表示:f[i]表示从[i,n)中选一点u合并0到u的所有石子,最优策略下Alice与Bob的分数之差。
- 状态划分:
- 不选i:f[i+1]
- 选i:pre[i] - f[i+1]
- 转移方程:f[i] = max(f[i + 1], pre[i] - f[i + 1])
class Solution {
public:
int stoneGameVIII(vector<int>& stones) {
int n = stones.size();
vector<int>s(n + 1, 0);
for(int i = 1; i <= n; i++)
s[i] = s[i - 1] + stones[i - 1];
vector<int>f(n + 1, 0);
f[n] = s[n];
for(int i = n - 1; i >= 2; i--)
f[i] = max(f[i + 1], s[i] - f[i + 1]);
return f[2];
}
};