#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;
}

 

相关文章:

  • 2021-12-03
  • 2021-12-14
  • 2021-04-14
  • 2021-09-12
  • 2021-10-24
  • 2021-12-21
  • 2021-04-03
  • 2022-01-15
猜你喜欢
  • 2021-08-03
  • 2021-09-25
  • 2022-01-29
  • 2021-06-06
  • 2021-08-16
  • 2021-10-26
  • 2021-12-05
相关资源
相似解决方案