大佬们的手速太可怕啦,现在23分钟的罚时排名都要出200啦。老板们也来试试吧,看看意念AC四道题需要几分钟~
周赛传送门
2148. 元素计数
思路一
时间复杂度:
空间复杂度:
的思路比较好想啦。外层循环枚举元素,内层循环检查是否满足要求即可。
class Solution {
public:
int countElements(vector<int>& nums) {
int cnt = 0;
for (auto num : nums) {
bool hasLt = false, hasGt = false;
for (auto n : nums) {
if (n < num) hasLt = true;
if (n > num) hasGt = true;
}
cnt += (hasLt && hasGt);
}
return cnt;
}
};
思路二
时间复杂度:
空间复杂度:
若一个数是其中的最大值或最小值,则必然不满足要求,反之则必然满足要求。因此,可先找出最大值和最小值,然后统计两者之外的数字有多少个。
class Solution {
public:
int countElements(vector<int>& nums) {
auto maxVal = *std::max_element(nums.begin(), nums.end());
auto minVal = *std::min_element(nums.begin(), nums.end());
int cnt = 0;
for (auto num : nums) {
cnt += (num != maxVal && num != minVal);
}
return cnt;
}
};
2149. 按符号重排数组
时间复杂度:
空间复杂度:
根据题意,重排后的偶数下标为0,2,4,6...,奇数下标为 1,3,5,7...。因此,在遍历过程中,按照奇偶性插入对应位置即可。
class Solution {
public:
vector<int> rearrangeArray(vector<int>& nums) {
vector<int> anw(nums.size(), 0);
int pos = 0, neg = 1;
for (auto num : nums) {
if (num > 0) {
anw[pos] = num;
pos += 2;
} else {
anw[neg] = num;
neg += 2;
}
}
return anw;
}
};
2150. 找出数组中的所有孤独数字
时间复杂度:
空间复杂度:
用哈希表记录每个数字出现的次数。然后遍历哈希表,检查元素是否仅出现一次且无邻居数字。
class Solution {
public:
vector<int> findLonely(vector<int>& nums) {
unordered_map<int, int> mark;
for (auto num : nums) {
mark[num]++;
}
vector<int> anw;
for (const auto &[num, cnt] : mark) {
if (cnt != 1) continue;
if (mark.count(num-1)) continue;
if (mark.count(num+1)) continue;
anw.push_back(num);
}
return anw;
}
};
2151. 基于陈述统计最多好人数
时间复杂度:
空间复杂度:
枚举所有情形,对于每种情形检查其中好人的陈述是否与当前情形冲突即可。对于不冲突的情形,记录好人的数量,最大值即为答案。详见注释。
class Solution {
public:
int maximumGood(vector<vector<int>>& stat) {
int n = stat.size();
// 使用位运算实现。
int mask = (1<<n);
// anw 记录答案
int anw = 0;
// 枚举情形 i。从低位开始数,第 k 个比特代表第 k 个人的身份,1 是好人,0 是坏人。
for (int i = 0; i < mask; i++) {
// status[k] 表示第 k 个人的身份,等价于第 k 个比特。这里预处理一下,为了后续方便使用。
bool status[15] = {0};
for (int k = 0, b = 1; k < n; k++, b <<= 1) {
status[k] = (b&i);
}
// cnt 记录当前情形的好人数量。
int cnt = 0;
for (int k = 0, b = 1; k < n; k++, b <<= 1) {
// 是坏人忽略。
if (!(b&i)) { continue;}
cnt++;
// 检查k的n次陈述是否与当前情形冲突。
for (int j = 0; j < n; j++) {
// k 的第 j 次陈述,明确表示了 j 的身份,但与status[j] 不符,冲突啦。
// 因此将 cnt 置为一个极小值,防止后续更新 anw。
if (2 != stat[k][j] && stat[k][j] != status[j]) {
cnt = -100;
}
}
}
// 更新 anw
anw = max(anw, cnt);
}
return anw;
}
};