题目地址:
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/description/
给定一个长 n n n数组 a a a,求最大的数对和,满足这两个数各个十进制位的和相等。不存在则返回 − 1 -1 −1。
枚举第二个数,用哈希表记录十进制位的和为 s s s的之前出现过的最大数是多少即可。代码如下:
class Solution {
public:
int maximumSum(vector<int> &a) {
int n = a.size();
unordered_map<int, int> mp;
auto f = [](int x) {
int sum = 0;
while (x) {
sum += x % 10;
x /= 10;
}
return sum;
};
int res = -1;
for (int i = 0; i < n; i++) {
int x = a[i], s = f(x);
auto [it, ins] = mp.emplace(s, x);
if (!ins) {
res = max(res, it->second + x);
it->second = max(it->second, x);
}
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。
本文介绍了一种计算给定十进制数转换为二进制后包含1的数量及位置的方法。通过位运算实现,返回一个数组,第一个元素表示二进制中1的总数,后续元素表示每个1的位置。

3149

被折叠的 条评论
为什么被折叠?



