面试题 01.02. 判定是否互为字符重排
代码实现(排序)
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
return s1 == s2;
}
};
2418. 按身高排序
代码实现(优先队列)
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
priority_queue<pair<int, string>> pq;
for (int i = 0; i < names.size(); i++) {
pq.push({heights[i], names[i]});
}
vector<string> ans;
while (pq.size()) {
auto [_, name] = pq.top();
pq.pop();
ans.push_back(name);
}
return ans;
}
};
2419. 按位与最大的最长子数组
代码实现(贪心)
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size();
int maxNum = *max_element(nums.begin(), nums.end());
int maxLen = 0;
for (int i = 0; i < n; i++) {
if (nums[i] != maxNum) continue;
int j = i + 1;
int curLen = 1;
while (j < n && nums[j] == nums[i]) {
j++;
curLen++;
}
maxLen = max(maxLen, curLen);
i = j;
}
return maxLen;
}
};
2420. 找到所有好下标
代码实现(前缀和)
class Solution {
public:
vector<int> goodIndices(vector<int>& nums, int k) {
int n = nums.size();
vector<int> increasingOrDecreasing(n);
for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1]) increasingOrDecreasing[i] = 0;
if (nums[i] < nums[i - 1]) increasingOrDecreasing[i] = -1;
if (nums[i] > nums[i - 1]) increasingOrDecreasing[i] = 1;
}
vector<int> notIncreasing(n, 1);
for (int i = 1; i < n; i++) {
if (increasingOrDecreasing[i] <= 0) notIncreasing[i] += notIncreasing[i - 1];
}
vector<int> notDecreasing(n , 1);
for (int i = 1; i < n; i++) {
if (increasingOrDecreasing[i] >= 0) notDecreasing[i] += notDecreasing[i - 1];
}
vector<int> ans;
for (int i = k; i < n - k; i++) {
if (notIncreasing[i - 1] >= k && notDecreasing[i + k] >= k) {
ans.push_back(i);
}
}
return ans;
}
};
2421. 好路径的数目
代码实现(并查集)
class Solution {
public:
int numberOfGoodPaths(vector<int> &vals, vector<vector<int>> &edges) {
int n = vals.size();
vector<vector<int>> g(n);
for (auto &e : edges) {
int x = e[0], y = e[1];
g[x].push_back(y);
g[y].push_back(x);
}
int id[n], fa[n], size[n];
iota(id, id + n, 0);
iota(fa, fa + n, 0);
fill(size, size + n, 1);
function<int(int)> find = [&](int x) -> int { return fa[x] == x ? x : fa[x] = find(fa[x]); };
int ans = n;
sort(id, id + n, [&](int i, int j) { return vals[i] < vals[j]; });
for (int x : id) {
int vx = vals[x], fx = find(x);
for (int y : g[x]) {
y = find(y);
if (y == fx || vals[y] > vx) continue;
if (vals[y] == vx) {
ans += size[fx] * size[y];
size[fx] += size[y];
}
fa[y] = fx;
}
}
return ans;
}
};