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

LeetCode OJ:Two Sum(两数之和)

时间:2015-10-05 18:12:58      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

给一个vector,一个value,要求求出vector之内的两数相加之和等于value的两个index。

这里的基本思想是用一个map先来保存vector元素的值与他们对应的index,然后循环vector,用value减去每个数之后,把差值直接放到map里面去寻找
看能不能找到对应的index,大体上就是这个思想,下面详见代码:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int, int> index;
 5         vector<int> result;
 6         int sz = nums.size();
 7         for (int i = 0; i < sz; ++i){
 8             index[nums[i]] = i;
 9         }
10         map<int, int>::iterator it;
11         for (int i = 0; i < sz; ++i){
12             if ((it = index.find(target - nums[i])) != index.end()){
13                 if (it->second == i) continue;//这一步要注意,防止找到的index与当前的i是相等的
14                 result.push_back(i + 1);
15                 result.push_back(it->second + 1);
16                 break;
17             }
18         }
19         return result;
20     }
21 };

 

LeetCode OJ:Two Sum(两数之和)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4856032.html

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