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

leetcode--Two Sum

时间:2016-06-24 10:47:07      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

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.

Example:

1 Given nums = [2, 7, 11, 15], target = 9,
2 Because nums[0] + nums[1] = 2 + 7 = 9,
3 return [0, 1].

通常很容易想到的解法是使用双层循环遍历给定的数组,查找是否有满足条件的两个数。代码如下:

 1 vector<int> addToTarget(vector<int> &num,int target)
 2 {
 3   vector<int> res;
 4   for(auto it1 = num.begin(); it1 != num.end();++it1)
 5     for(auto it2 = num.begin();it2 != num.end();++it2)
 6       {
 7         if(*it1 + *it2 == target && it1 != it2)
 8           {
 9             res.push_back(static_cast<int>(it1 - num.begin()));
10             res.push_back(static_cast<int>(it2 - num.begin()));
11             return res;
12           }
13       }
14 }

但是使用双层循环的时间复杂度为O(n2),且两次循环且条件不满足时,数组的某些元素会被多次遍历,也就是处理当前节点需要依赖于之前的部分结果,如果我们能够保存已遍历的元素的状态,便可减少这种浪费的发生。所以考虑使用哈希表来存储状态,因为哈希表的存储和读取时间复杂度为O(1)。代码如下:

 1 vector<int> addToTarget(vector<int> &num,int target)
 2 {
 3   vector<int> res(2);
 4   unordered_map<int,int> hashMap;
 5   for(auto it=num.begin();it != num.end(); ++it)
 6     {
 7       if(hashMap.count(target - *it))
 8         {
 9           res[0]=hashMap[target-*it];
10           res[1]=static_cast<int>(it-num.begin());
11           return res;
12         }
13       hashMap[*it] = static_cast<int>(it-num.begin());
14     }
15 }

我们使用hashMap的键来保存给定数组的值,使用hashMap的值来保存给定数组的下标。使用一个循环遍历数组,如果与当先遍历值相加等于targe的值存在于已保存的hashMap中时,记录当前下标和满足值得下标并返回。时间复杂度为O(n)。

leetcode--Two Sum

标签:

原文地址:http://www.cnblogs.com/treecarrybear/p/5613290.html

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