Problem:
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
Solution(1):
我的初始解法,比较简单,但是时间复杂度过高,O(n^2)。
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int>::iterator it;
vector<int>::iterator im;
vector<int> result;
int i =1;
int j = 1;
int index1;
int index2;
for(it = nums.begin();it < nums.end() -1;it++)
{
for(im= it+1;im < nums.end();im++)
{
j++;
if(*it + * im == target)
{
index1 =i;
index2 = j;
}
}
i++;
j=i;
}
result.push_back(index1);
result.push_back(index2);
return result;
}
Solution(2):
使用hash_map的,解法,利用它查找数据为常数级的优点,底层为哈希表实现。但是十分耗资源,是以空间换时间。
时间复杂度为O(n)
vector<int> twoSum(vector<int>& nums, int target)
{
int index1,index2;
vector<int> result;
vector<int>::iterator imt;
hash_map<int,int> hmap;
hash_map<int,int>::iterator it; //first-key,second-value
for(int i=0;i < nums.size();i++)
{
it = hmap.find(nums[i]); //查找这个键值
if(it == hmap.end()) //即不存在
{
//插入值
hmap.insert(pair<int,int>(nums[i],i));
}
//同时查找是否存在target-nums[i]的值
it = hmap.find(target - nums[i]);
if(it != hmap.end()) //如果存在则OK
{
if(it->second < i) //防止查找时查到同一个值上
{
index1 = it->second;
index2 = i;
}
}
}
index1++;
index2++;
result.push_back(index1);
result.push_back(index2);
return result;
}
Solution(3):
使用Map的方法,底层是红黑树,利用的是二分查找,所以它的查找时间复杂度为O(log(n))。
在该题目中为O(nlog(n))。
用map可在leetcode上运行通过。
vector<int> twoSum(vector<int>& nums, int target)
{
int index1,index2;
vector<int> result;
map<int,int> my_map;
map<int,int>::iterator it;
for(int i=0;i<nums.size();i++)
{
it = my_map.find(nums[i]);
if(it == my_map.end())
{
my_map.insert(pair<int,int>(nums[i],i));
}
it = my_map.find(target - nums[i]);
if(it != my_map.end())
{
if(it->second < i)
{
index1 = it->second;
index2 = i;
}
}
}
index1++;
index2++;
result.push_back(index1);
result.push_back(index2);
return result;
}