A 边界上的蚂蚁
模拟
class Solution {
public:
int returnToBoundaryCount(vector<int> &nums) {
int s = 0;
int res = 0;
for (auto x: nums) {
s += x;
if (s == 0)
res++;
}
return res;
}
};
B 将单词恢复初始状态所需的最短时间 I
枚举:若经过 i i i 秒后 w o r d word word 可以恢复到其初始状态,则说明 w o r d word word 长为 n − i × k n-i\times k n−i×k的后缀与长为 n − i × k n-i\times k n−i×k的前缀相等, n n n 为 w o r d word word 的长度,升序枚举 i i i 直到满足条件
class Solution {
public:
int minimumTimeToInitialState(string word, int k) {
int n = word.size();
int i = 1;
for (; i * k < n; i++) {
int tag = 1;
for (int j = i * k; j < n; j++)
if (word[j] != word[j - i * k])
tag = 0;
if (tag)
return i;
}
return i;
}
};
C 找出网格的区域平均强度
模拟:枚举网格中的 3 × 3 3\times3 3×3 的子网格,判断是否是区域,同时记录各位置所属于的区域数和所属于的区域的平均强度之和,最后求网格的区域平均强度
class Solution {
public:
vector<vector<int>> resultGrid(vector<vector<int>> &image, int threshold) {
int m = image.size(), n = image[0].size();
vector<vector<int>> tot(m, vector<int>(n));
vector<vector<int>> cnt(m, vector<int>(n));
for (int i = 0; i + 2 < m; i++)
for (int j = 0; j + 2 < n; j++) {
int tag = 1;//判断是否是区域
for (int x = i; x < i + 3; x++)
for (int y = j + 1; y < j + 3; y++)
if (abs(image[x][y] - image[x][y - 1]) > threshold)
tag = 0;
for (int y = j; y < j + 3; y++)
for (int x = i + 1; x < i + 3; x++)
if (abs(image[x][y] - image[x - 1][y]) > threshold)
tag = 0;
if (tag) {
int s = 0;
for (int x = i; x < i + 3; x++)
for (int y = j; y < j + 3; y++)
s += image[x][y];
s /= 9;//当前区域的平均强度
for (int x = i; x < i + 3; x++)
for (int y = j; y < j + 3; y++) {
cnt[x][y]++;//所属区域数目+1
tot[x][y] += s;//所属区域的平均强度之和+s
}
}
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (!cnt[i][j])
tot[i][j] = image[i][j];
else
tot[i][j] /= cnt[i][j];
return tot;
}
};
D 将单词恢复初始状态所需的最短时间 II
字符串哈希 + 枚举:若经过 i i i 秒后 w o r d word word 可以恢复到其初始状态,则说明 w o r d word word 长为 n − i × k n-i\times k n−i×k的后缀与长为 n − i × k n-i\times k n−i×k的前缀相等, n n n 为 w o r d word word 的长度,升序枚举 i i i 直到满足条件
class Solution {
public:
int minimumTimeToInitialState(string word, int k) {
int n = word.size();
int i = 1;
srand(time(0));
shash h(word, 2333 + rand() % 100, 1e9 + rand() % 100);
for (; i * k < n; i++) {
if (h(i * k, n - 1) == h(0, n - 1 - i * k))//s[i*k,n-1]和s[0,n-1-i*k]是否相等
return i;
}
return i;
}
class shash {//字符串哈希模板
public:
using ll = long long;
vector<ll> pres;
vector<ll> epow;
ll e, p;
shash(string &s, ll e, ll p) {
int n = s.size();
this->e = e;
this->p = p;
pres = vector<ll>(n + 1);
epow = vector<ll>(n + 1);
epow[0] = 1;
for (int i = 0; i < n; i++) {
pres[i + 1] = (pres[i] * e + s[i]) % p;
epow[i + 1] = (epow[i] * e) % p;
}
}
ll operator()(int l, int r) {
ll res = (pres[r + 1] - pres[l] * epow[r - l + 1] % p) % p;
return (res + p) % p;
}
};
};