写一段C++代码 给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值 target 的那两个整数,并深回它们的数组晅下标。 你可以假设每种输入只会对应一个答案,并且你不能使用两次
时间: 2024-12-15 11:19:01 浏览: 23
当然,这是一个经典的数组两数之和问题,可以使用哈希表来解决。以下是使用 C++ 编写的解决方案:
```cpp
#include <iostream>
#include <unordered_map>
std::pair<int, int> twoSum(std::vector<int>& nums, int target) {
std::unordered_map<int, int> hashTable;
for (size_t i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (hashTable.find(complement) != hashTable.end()) {
return {hashTable[complement], i};
}
hashTable[nums[i]] = i;
}
throw std::runtime_error("No solution found.");
}
int main() {
std::vector<int> nums = {2, 7, 11, 15}; // 示例数组
int target = 9; // 目标和
auto result = twoSum(nums, target);
std::cout << "The two numbers with sum " << target << " are at indices " << result.first << " and " << result.second << "." << std::endl;
return 0;
}
```
在这个代码中,我们遍历数组,对于每个元素,我们在哈希表中查找是否存在目标和减去当前元素的补数。如果找到,就找到了一对和为目标值的数及其下标;如果没有找到,则将当前元素及其下标存入哈希表继续搜索。如果遍历完整个数组都没有找到解,函数会抛出异常。
阅读全文
相关推荐
















