#include<iostream> #include<unordered_map> #include<vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> hashtable; for (int i = 0; i < nums.size(); i++) { hashtable[nums[i]] = i; // nums数组的值为key,下标为value } for (int i = 0; i < nums.size(); i++) { if (hashtable.find(target - nums[i]) != hashtable.end() && hashtable[target - nums[i]] != i) { return { i, hashtable[target - nums[i]] }; } } } }; int main() { vector<int> nums = { 2, 4, 1, 6, 8 }; int target = 5; int length = nums.size(); vector<int> result; Solution solution; result = solution.twoSum(nums, target); if (!result.empty()) for (int i = 0; i < result.size(); i++) { cout << result[i] << ' '; } else cout << "不存在" << endl; return 0; }