[leetCode][012] Two Sum (1)

【题目】:

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

【题意】:

  题目中要求输入一个整形数组以及一个target,找出该整型数组中这样两个元素,使得这两个元素之和等于指定target的值。 题目中假设该两个元素必然存在,并且是只有一组(所以相对简单),返回的是这两个元素的index值(数组Index从1开始)。

 

【坑】:

  我们拿到这个题目,首先能够想到的就是两次遍历,但是这样时间复杂度为O(n^2),无法通过leetCode的OJ测试。所以需要找其他方法。必然要小于O(n^2)复杂度才行。

 

【key point】:

  我们经常会使用空间换取时间的方法来获取较小的时间复杂度。因此增加必要的数据结构来减少时间复杂度。这道题目一样,我们增加一个map结构,key为数组元素值,value为其在数组中对应的index。每次遍历到数组元素便去map结构中查找对应的补数,如果存在,那就说明找到了。如果没存在就记录当前元素以及其index,直到结束。

 

【解答】:

 1 class Solution{
 2 public:
 3      // O(n) runtime, O(n) space
 4     // We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
 5     std::vector<int> twoSum(std::vector<int>& numbers, int target){
 6         std::vector<int> vecRet;
 7         std::map<int, int> mapIndex;
 8         for (size_t i = 0; i < numbers.size(); ++i){
 9             if (0 != mapIndex.count(target - numbers[i])){
10                 int nIndex = mapIndex[target - numbers[i]];
11                 // 当前存储的Index肯定比i要小,注意要排除i
12                 if (nIndex < i){
13                     vecRet.push_back(nIndex + 1);
14                     vecRet.push_back(i + 1);
15                     return vecRet;
16                 }
17             } else {
18                 mapIndex[numbers[i]] = i;
19             }
20         }
21         return vecRet;
22     } // twoSum
23 };

【leetCode Submission】

【运行结果】:

 

希望各位看官不吝赐教,小弟感恩言谢~

posted @ 2015-01-15 20:34  菜鸟加贝的爬升  阅读(340)  评论(0编辑  收藏  举报