码迷,mamicode.com
首页 > 其他好文 > 详细

(Leetcode) Two Sum

时间:2018-04-29 21:15:38      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:app   push   break   color   NPU   ppi   const   numbers   ecif   

題目:

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

(Leetcode) Two Sum

标签:app   push   break   color   NPU   ppi   const   numbers   ecif   

原文地址:https://www.cnblogs.com/ollie-lin/p/8971810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!