A
class Solution {
public:
int findFinalValue(vector<int>& nums, int original) {
for (int i = 1; i <= 1000; i ++ ) {
for (auto x : nums) {
if (x == original) {
original *= 2;
}
}
}
return original;
}
};
B
class Solution {
public:
int a[100010];
int sum0[100010], sum1[100010];
vector<int> maxScoreIndices(vector<int>& nums) {
vector<int> ans;
for (int i = 0; i < nums.size(); i ++ )
a[i + 1] = nums[i];
int n = nums.size();
for (int i = 1; i <= n; i ++)
sum0[i] = sum0[i - 1] + (a[i] == 0);
for (int i = 1; i <= n; i ++)
sum1[i] = sum1[i - 1] + (a[i] == 1);
int maxx = 0;
for (int i = 0; i <= n; i ++ )
if (sum0[i] + sum1[n] - sum1[i] > maxx)
maxx = sum0[i] + sum1[n] - sum1[i];
for (int i = 0; i <= n; i ++ )
if (sum0[i] + sum1[n] - sum1[i] == maxx)
ans.push_back(i);
return ans;
}
};
C
hash
class Solution {
public:
long long p[20010];
long long h[20010];
char c[20010];
string subStrHash(string s, int power, int modulo, int k, int hashValue) {
int n = s.size();
reverse(s.begin(), s.end());
p[0] = 1 % modulo;
for (int i = 1; i <= n; i ++ )
p[i] = p[i - 1] * power % modulo;
int start, end;
for (int i = 0; i < n; i ++ )
c[i + 1] = s[i];
for (int i = 1; i <= n; i ++ )
h[i] = (h[i - 1] * power % modulo + (c[i] - 'a'+ 1) % modulo) % modulo;
function<int(int, int)> get = [&](int l, int r) {
int k = ((h[r] - h[l - 1] * p[r - l + 1] % modulo) % modulo + modulo) % modulo;
return k;
};
for (int i = 1; i + k - 1 <= n; i ++ ) {
if (get(i, i + k - 1) == hashValue) {
start = i, end = i + k - 1;
}
}
string ans;
for (int i = start; i <= end; i ++ )
ans += c[i];
reverse(ans.begin(), ans.end());
return ans;
}
};
D
并查集 + 二进制压缩
注意此处为集合所以是不考虑顺序的,所以直接用二进制压缩表示即可
class Solution {
unordered_map<int, int> fa, size;
int groups, maxSize = 0;
int find(int x) {
return fa.count(x) && fa[x] != x ? fa[x] = find(fa[x]) : x;
}
void merge(int x, int y) {
if (!fa.count(y)) return;
x = find(x);
y = find(y);
if (x == y) return;
fa[x] = y;
size[y] += size[x];
maxSize = max(maxSize, size[y]);
--groups;
}
public:
vector<int> groupStrings(vector<string> &words) {
groups = words.size();
for (auto &word : words) {
int x = 0;
for (char ch: word) {
x |= 1 << (ch - 'a');
}
fa[x] = x;
++size[x];
maxSize = max(maxSize, size[x]);
if (size[x] > 1) --groups;
}
for (auto &[x, _]: fa) {
for (int i = 0; i < 26; ++i) {
if ((x >> i) & 1) {
merge(x, x ^ (1 << i));
for (int j = 0; j < 26; ++j) {
if (((x >> j) & 1) == 0) {
merge(x, x ^ (1 << i) | (1 << j));
}
}
} else {
merge(x, x | (1 << i));
}
}
}
return {groups, maxSize};
}
};