# 115. 组装手机

这道题是比较难得哈希表题目。 把代码随想录哈希表章节理解透彻,做本题没问题。

思路是

  1. 用哈希表记录 外壳售价 和 手机零件售价 出现的次数
  2. 记录总和出现的次数
  3. 遍历总和,减去 外壳售价,看 手机零件售价出现了几次
  4. 最后累加,取最大值

有一个需要注意的点: 数字可以重复,在计算个数的时候,如果计算重复的数字

例如 如果输入是

4
1 1 1 1
1 1 1 1
1
2
3

那么输出应该是 4, 外壳售价 和 手机零件售价 是可以重复的。

代码如下:

#include <iostream> 
#include <vector>
#include <unordered_set>
#include <unordered_map>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector<int> aVec(n, 0);
    vector<int> bVec(n, 0);
    unordered_map<int, int > aUmap;
    unordered_map<int, int > bUmap;
    for (int i = 0; i < n; i++) {
        cin >> aVec[i];
        aUmap[aVec[i]]++;
    }
    for (int i = 0; i < n; i++) {
        cin >> bVec[i];
        bUmap[bVec[i]]++;
    }
    unordered_set<int > uset;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++){
            uset.insert(aVec[i] + bVec[j]); 
        }
    }
    int result = 0;
    for (int sum : uset) {
        //cout << p.first << endl;
        int count = 0;
        for (pair<int, int> p : aUmap) {
            //cout << p.first - aVec[i] << endl;
            if (sum - p.first > 0 && bUmap[sum - p.first] != 0) {
                count += min(bUmap[sum - p.first], p.second);
            }
        }
        result = max(result, count);
    }
    cout << result << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
上次更新:: 3/4/2025, 5:49:45 PM
@2021-2025 代码随想录 版权所有 粤ICP备19156078号