2180. 统计各位数字之和为偶数的整数个数
Code
class Solution {
public:
int countEven(int num) {
int res = 0;
for (int i = 1; i <= num; i++) {
int t = i, sum = 0;
while (t) {
sum += t % 10;
t /= 10;
}
if (sum % 2 == 0) res++;
}
return res;
}
};
2181. 合并零之间的节点
Code
/**
* 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) {
auto dummy = new ListNode(-1), cur = dummy;
int sum = 0;
while (head) {
if (head->val != 0) sum += head->val;
else {
cur = cur->next = new ListNode(sum);
sum = 0;
}
head = head->next;
}
return dummy->next->next;
}
};
2182. 构造限制重复的字符串
题目描述
解题思路
本题的做法参考此处
本题我一开始想的是用优先队列的做法,但是可能由于自己的代码熟练度还不够,没成功A出来(真的是一道送分题)
Code
class Solution {
public:
int cnt[26];
string repeatLimitedString(string s, int repeatLimit) {
int n = s.length();
for (int i = 0; i < n; i++) {
cnt[s[i] - 'a']++;
}
string res;
int last = -1, time = 0; // last用于记录上一个添加的字符, time用于记录添加次数
for (int i = 0; i < n; i++) {
int t = -1;
for (int j = 0; j < 26; j++) {
if (cnt[j] && (time < repeatLimit || j != last))
t = j; // 找到最大的字符下标
}
if (t == -1) return res; // 如果t == -1 说明上面的过程中没有找到符合条件的或者剩余数量已经都为0了
if (last == t) time++;
else last = t, time = 1;
res += (char)(t + 'a'); // 转换为字符后再加进去
cnt[t]--; // 数量减一
}
return res;
}
};
6015. 统计可以被 K 整除的下标对数目
题目描述
解题思路
可以参考这个题解
TIPS:对于因数的预处理只能进行一次 不然会TLE!
Code
const int N = 100010;
vector<int> divs[N];
bool flag = false;
class Solution {
public:
long long countPairs(vector<int>& nums, int k) {
if (!flag) { // 只进行一次预处理
for (int i = 1; i < N; i++)
for (int j = i; j < N; j += i)
divs[j].push_back(i);
flag = true;
}
long long ans = 0;
unordered_map<int, int> cnt;
for (auto v : nums) {
ans += cnt[k / __gcd(k,v)];
//每次都在上一句处理完后再加入,这样可以做到对于每个nums[j]都只能计数前面出现过的的nums[i],符合i < j
for (auto x : divs[v]) cnt[x] ++;
}
return ans;
}
};