第一题:统计能整除数字的位数
题目链接
代码
class Solution {
public:
int countDigits(int num) {
int cnt = 0, a = num;
while(num) {
int n = num % 10;
if(a % n == 0) cnt ++;
num /= 10;
//cout << n << " " << cnt << endl;
}
return cnt;
}
};
第二题:数组乘积中的不同质因数数目
题目链接
代码
class Solution {
public:
int distinctPrimeFactors(vector<int>& nums) {
unordered_map<int,int> heap;
for (auto& x : nums) {
for (int i = 2; i <= x / i; i ++) {
if(x % i == 0) {
int s = 0;
while(x % i == 0) x /= i, s ++;
heap[i] += s;
}
}
if(x > 1) heap[x] ++;
}
for (auto& x : heap) cout << x.first << " " << x.second << endl;
return heap.size();
}
};
第三题:将字符串分割成值不超过 K 的子字符串
题目链接
代码
#define LL long long
class Solution {
public:
int minimumPartition(string s, int k) {
LL t = 0;
int ans = 1;
for (char c : s) {
if (c - '0' > k)
return -1;
if (t * 10 + c - '0' > k) {
ans ++;
t = 0;
}
t = t * 10 + c - '0';
}
return ans;
}
};
第四题:范围内最接近的两个质数
题目链接
代码
class Solution {
public:
bool is_prime(int x) {
if (x < 2) return false;
for (int i = 2; i <= x / i; i ++) {
if (x % i == 0) return false;
}
return true;
}
vector<int> closestPrimes(int left, int right) {
vector<int> primes;
for (int i = left; i <= right; i ++) {
if(is_prime(i)) primes.push_back(i);
}
vector<int> res(2, -1);
int d = 1e8;
for (int i = 1; i < primes.size(); i ++ ) {
int a = primes[i - 1], b = primes[i];
if (b - a < d) {
d = b - a;
res[0] = a, res[1] = b;
}
}
return res;
}
};
总结
代码全部是自己提交的代码,有些地方还有调试痕迹,其中第二题选用了map,其实还可以使用set来存储。
本次"完美地"做出来看前两道题,第三题和第四题少有磕绊,第一次参加周赛。
第三题因为使用了双指针不知道怎么超时了,最后使用了小小的贪心。
第四题在最后判断最小值的时候出现了错误,把变量d定义的位置弄错了。
痛苦,啊啊啊。
好可惜!!!