[leetcode 1] Two Sum

来源:互联网 发布:开通服务器端口 编辑:程序博客网 时间:2024/03/29 17:14

题目:

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

思路:

方法一:排序+夹逼
1. 对数组进行排序。由于需要记录原始数据的位置,故创建一个数据结构Node,记录两种信息,一为原始数组中的数据,二为该数据在原始数据中的位置。使用Node结构重新构造数据,并对其排序。排序的时间复杂度为O(nlogn)。
2.对排好序的数组进行夹逼,一个指针指向第一个数据,一个指针指向最后一个,若二者所指数据之和等于target,则保存Node所记录数据位置,中断查找;若上述和小于target,则第一个指针右移;若和大于target,则右边指针左移。
3.由于第二步相当于对数组进行了一次遍历,故第二步时间复杂度为O(n)。故此方法时间复杂度为O(nlogn)+O(n)=O(nlogn)。

方法二:map
1.使用map结构,将数组中数据以此存入map中,每个map数据包含两部分内容,一为原始数据,二为该数据在原始数组中位置。
2.遍历map结构,对于当前数据num,在map中查找target-num,由于map中find算法的时间复杂度为O(logn),该算法遍历n个数据,故时间复杂度为O(nlogn)。

方法三:哈希
1.对于方法二,将map改用hash_map实现。
2.由于哈希表可以在常数时间内查找数据,故此方法的时间复杂度为O(1)*N=O(n);
3.leetcode无hash_code结构,该方法未通过。

代码:

1.方法一:
struct Node{int num;int poi;};bool cmp(Node a,Node b){return a.num<b.num;}class Solution{public:vector<int> twoSum(vector<int> &numbers,int target){vector<Node> arr;vector<int> result;for(int i=0;i!=numbers.size();++i){Node tmp;tmp.num=numbers[i];tmp.poi=i;arr.push_back(tmp);}sort(arr.begin(),arr.end(),cmp);for(int i=0,j=arr.size()-1;i!=j;){if(arr[i].num+arr[j].num == target){result.push_back(++arr[i].poi);result.push_back(++arr[j].poi);break;}else if(arr[i].num+arr[j].num<target){++i;}else if(arr[i].num+arr[j].num>target){--j;}}return result;}}

方法二:
class Solution{public:vector<int> twoSum(vector<int> &numbers,int target){hash_map<int,int> numpoi;vector<int> result;for(int i=0;i!=numbers.size();++i){numpoi[numbers[i]]=i;}for(int i=0;i!=numbers.size();++i){int dif=target-numbers[i];hash_map<int,int>::iterator it=numpoi.find(dif);if(it!=numpoi.end() && numpoi[dif]>i){result.push_back(++i);result.push_back(++numpoi[dif]);break;}}return result;}};

补充:

1.hash_map采用哈希表实现,map采用红黑树实现,其数据结构不同
2.hash_map的查找效率较高,属于常数级别;map的查找速度为logn
3.如果对效率要求较高,特别是在数量达到一定量级时,可以考虑采用hash_map,但是哈希算法以空间换取时间,若对内存要求较为严格,则需慎重考虑hash_map。



0 0
原创粉丝点击