C++巧用哈希表:高效找出和为指定值且差值最小的两数
这个问题可以通过使用哈希表(unordered_set)来高效解决。我们可以在遍历数组时,检查当前元素与目标值n的差值是否已经存在于哈希表中。如果存在,则说明找到了两个数,它们的和等于n。否则,将当前元素插入哈希表中。 以下是C++代码实现: ```cpp #include <iostream> #include <unordered_set> #include <vector> #include <algorithm> using namespace std; pair<int, int> findPairWithSum(const vector<int>& nums, int n) { unordered_set<int> seen; pair<int, int> result = {-1, -1}; int minDiff = INT_MAX; for (int num : nums) { int complement = n - num; if (seen.find(complement) != seen.end()) { int currentDiff = abs(num - complement); if (currentDiff < minDiff) { minDiff = currentDiff; result = {min(num, complement), max(num, complement)}; } } seen.insert(num); } return result; } int main() { int n, m; cin >> n >> m; vector<int> nums(m); for (int i = 0; i < m; ++i) { cin >> nums[i]; } pair<int, int> result = findPairWithSum(nums, n); if (result.first != -1) { cout << result.first << " " << result.second << endl; } else { cout << "No Answer" << endl; } return 0; } ``` 代码解释: 1. unordered_set<int> seen: 用于存储已经遍历过的数字。 2. pair<int, int> result: 用于存储最终找到的两个数。 3. int minDiff: 用于记录当前找到的最小差值。 4. for (int num : nums): 遍历数组中的每个数字。 5. int complement = n - num: 计算当前数字与目标值n的差值。 6. if (seen.find(complement) != seen.end()): 检查差值是否已经存在于哈希表中。 7. int currentDiff = abs(num - complement): 计算当前两个数的差值。 8. if (currentDiff < minDiff): 如果当前差值小于最小差值,则更新结果和最小差值。 9. seen.insert(num): 将当前数字插入哈希表中。 需要注意的逻辑点: 1. 确保输入的数字都是正整数且小于1000000。 2. 如果有多组数据满足条件,输出差值最小的一组。 3. 如果找不到满足条件的两个数,输出“No Answer”。 ######[AI写代码神器 | 568点数解答 | 2025-02-12 08:50:33]
- C#工程师必知:数组、链表、哈希、队列、栈数据结构优缺点大揭秘! (百度文心 | 561点数解答 | 2023-11-09 17:56:30)275
- 巴黎奥运:中国女排淘汰赛对决土耳其,朱婷成致胜关键!(字节豆包 | 448点数解答 | 2024-08-06 15:59:48)178
- 旅行售货员问题:详细步骤剖析与贪心算法Python代码实现(字节豆包 | 444点数解答 | 2024-12-17 03:32:59)288
- Dev C++ 实现旅行售货员问题:最小路程路线代码与详细解析 (字节豆包 | 448点数解答 | 2024-12-17 03:33:42)193
- C++ 求解 P1020 小核桃与删除字符串问题:双指针与枚举策略 (字节豆包 | 330点数解答 | 2026-02-07 18:40:10)35
- 用 Pandas 深度剖析数据:从读取到统计分析全流程实战(GPT | 642点数解答 | 2024-06-30 15:39:49)375
- 用 Pandas 深入分析招聘数据:从数据读取到可视化全流程解析(GPT | 1539点数解答 | 2024-06-30 15:56:50)387
- C++ 破解数字游戏:找出数组添加全排列后相同数字最大数量(字节豆包 | 456点数解答 | 2025-02-27 18:56:24)290
- C++助力小小李老师:求解数组添加排列后最多相同数字数量(字节豆包 | 424点数解答 | 2025-03-01 14:46:52)234
- C++助力小小李老师:破解数组数字游戏最高得分之谜(字节豆包 | 434点数解答 | 2025-03-05 07:50:34)253
- C++ 助力小小李老师玩转数字游戏,找出数组最大相同元素次数!(DeepSeek | 1118点数解答 | 2025-03-25 21:11:51)207
- C++ 助力小小李老师:解决数组添加排列找最大重复元素难题(DeepSeek | 833点数解答 | 2025-03-26 17:06:19)192