【2022/03/20-第281场单周赛】复盘

总结
无。
Q1.统计各位数字之和为偶数的整数个数
RATING:1257
模拟。
class Solution {
public:
int countEven(int num) {
int ret = 0;
for(int i = 1; i <= num; ++i){
int x = i, t = 0;
while(x){
t += x % 10;
x /= 10;
}
if(t % 2 == 0) ++ret;
}
return ret;
}
};
Q2.合并零之间的节点
RATING:1333
一遍合并,一遍去0。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode* l = head, *t = head->next, *r = head->next;
while(l->next){
while(r->val != 0){
if(r != l->next)
l->next->val += r->val;
r = r->next;
}
l->next->next = r;
l = r;
r = r->next;
}
ListNode* temp = head->next;
while(temp){
temp->next = temp->next->next;
temp = temp->next;
}
head = head->next;
return head;
}
};
Q3.构造限制重复的字符串
RATING:1680
模拟。
class Solution {
public:
string repeatLimitedString(string str, int rl) {
int h[26] = {0}, n = str.size();
for(auto i : str) ++h[i - 'a'];
string s;
int r = 0;
while(n--){
for(int i = 25; i >= 0; --i){
if(h[i] > 0 && r < rl){
s += (char)(i + 'a');
--h[i];
if(s.size() != 1 && s.back() == s[s.size() - 2]) ++r;
else r = 1;
break;
}
else if(h[i] > 0 && r == rl && i != s.back() - 'a'){
s += (char)(i + 'a');
--h[i];
r = 1;
break;
}
}
}
return s;
}
};
Q4.统计可以被 K 整除的下标对数目
Rating:2246
对每个数x,要找到y,就是找到k/gcd(x, k)出现的次数。筛一筛即可。
class Solution {
public:
using ll = long long;
int gcd(int x, int y){
if(x < y) swap(x, y);
while(x % y){
int t = y;
y = x % y;
x = t;
}
return y;
}
long long countPairs(vector<int>& nums, int k) {
int mx = max(k, *max_element(nums.begin(), nums.end()));
int cnt[mx + 1];
memset(cnt, 0, sizeof(cnt));
ll ret = 0;
for(auto i : nums) cnt[i]++;
for(int i = 1; i <= mx; ++i){
for(int j = i * 2; j <= mx; j += i)
cnt[i] += cnt[j];
}
for(auto i : nums) ret += cnt[k / gcd(k, i)];
for(auto i : nums) if((ll) i * i % k == 0) --ret;
return ret / 2;
}
};
浙公网安备 33010602011771号