码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode] Two Sum (C++)

时间:2014-11-02 00:36:25      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   div   

题目:

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

Tag:

Array; Hash Table

体会:

啊哈哈,这道题一次成功,虽然版本跟下面这个不一样,但是思路是一样的。

这个题很巧妙的用了map,因为是找两个数凑起来能是target, 所以遇到一个数,你就知道了它应该和谁去凑对,虽然不知道能凑对的这个数是否在array中存在又或者存在在什么地方。搞一个<number, index>的map, 记录每个数字出现的位置。逐个去检查数字,看看他要凑成对的那个数字是不是已经存在了即可。

P.S. 我的map里直接存的是要去找的那个数。比如target=9, 现在在位置0遇到了2,那我就存一个map[9-2]=0,然后检查的时候就可以直接去keys里面找有没有7了。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4             int n = numbers.size();
 5             vector<int> result;
 6             map<int, int> index;
 7             for (int i = 0; i < n; i++) {
 8                 if (index.count(numbers[i]) != 0) {
 9                     // if exists
10                     result.push_back(index[numbers[i]] + 1);
11                     result.push_back(i + 1);
12                     break;
13                 } 
14                 index[target - numbers[i]] = i; 
15             }
16             return result;
17     }
18 };

 

[Leetcode] Two Sum (C++)

标签:style   blog   io   color   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/stevencooks/p/4068004.html

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