[LeetCode] 1 Two Sum

   先前初学了《大话数据结构》,然后在网上看到了LeetCode的测试,于是开始刷题,第一题就是排行榜首位

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.

从而在网上找到了3个思路:

思路1:对于每一个元素,遍历寻找另一个元素使得和为target,时间复杂度O(n^2),这也是我最先使用的方式。

loop1 i=0 to size-2
    loop2 j=i+1 to size-1
        if(vs[i]+vs[j]=target) 跳出循环
找到i+1,j+1

思路2:先排序,然后首尾两个指针向中间靠拢,两指针所指元素大于target,移动尾指针,小于target移动头指针,直至找到结果或者两个指针相遇。时间复杂度O(nlogn)。此方法可推广值3Sum,4Sum等。

sort(vs[])
loop i=0,i=size-1;i!=j;;
    if vs[i]+vs[j]>target
        j--;
    if vs[i]+vs[j]<target
        i++;
    else
        找到,返回

思路3:利用hashmap,将每个元素值作为key,数组索引作为value存入hashmap,然后遍历数组元素,在hashmap中寻找与之和为target的元素。 时间复杂度O(n),空间复杂度O(n)。然而使用hash_map时却无法实现,想到map应用红黑树虽然时间效率低于hash_map,但依然蛮高的。

 1 vector<int> twoSum(vector<int> vs, int target)
 2 {
 3     map<int,int> hm;
 4     vector<int> result;
 5     vector<int>::size_type i,j;
 6     for(i=0;i!=vs.size();i++)
 7         hm.insert(pair<int,int>(vs[i],i));
 8     for(i=0;i!=vs.size();i++)
 9     {
10         map<int,int>::iterator iter=hm.find(target-vs[i]);
11         if(iter!=hm.end()&&iter->second!=i)//不重复并且不为空
12         {
13             j=iter->second;
14             if(i<j)
15             {
16                 result.push_back(i+1);
17                 result.push_back(j+1);
18             }
19             else{
20                 result.push_back(j+1);
21                 result.push_back(i+1);
22             }
23         }
24     }
25     return result;
26 }

ps:第一次做这种题,花了两天的时间完成并记录下来。 

posted @ 2015-02-05 18:14  aorora  阅读(120)  评论(0编辑  收藏  举报