(Leetcode) Two Sum

題目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Code :

 1 class Solution
 2 {
 3 public:
 4     vector<int> twoSum(vector<int>& nums, int target)
 5     {
 6         unordered_map<int, int> mapping;
 7         vector<int> result;
 8 
 9         for (int i = 0; i < nums.size(); i++)
10         {
11             mapping[nums[i]] = i;
12         }
13 
14         for (int i = 0; i < nums.size(); i++)
15         {
16             const int gap = target - nums[i];
17             if (mapping.find(gap) != mapping.end() && mapping[gap] > i)
18             {
19                 result.push_back(i);
20                 result.push_back(mapping[gap]);
21                 break;
22             }
23         }
24 
25         return result;
26     }
27 };

猜你喜欢

转载自www.cnblogs.com/ollie-lin/p/8971810.html