/*
- @lc app=leetcode id=1 lang=cpp
- [1] Two Sum
- https://leetcode.com/problems/two-sum/description/
- algorithms
- Easy (40.14%)
- Total Accepted: 1.4M
- Total Submissions: 3.5M
- Testcase Example: ‘[2,7,11,15]\n9’
- 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, and you may
- not use the same element twice.
- Example:
- Given nums = [2, 7, 11, 15], target = 9,
- Because nums[0] + nums[1] = 2 + 7 = 9,
- return [0, 1].
/
/*
- Note: The returned array must be malloced, assume caller calls free().
/
第一次accept的代码,暴力搜索
int twoSum(int* nums, int numsSize, int target)
{
int i,j;
int *solution=(int *)malloc(sizeof(int)*2);
for(i=0;i<numsSize;i++)
{
for(j=i+1;j<numsSize;j++)
{
if(nums[i]+nums[j]==target)
{
solution[0]=i;
solution[1]=j;
return solution;
}
}
}
return solution;
}
使用哈希表,先把value-index存到哈希表。
然后使用result=target-value,如果result等于哈希表中的value,则返回两个数index。
注意两个index不能相同,下面是c++的实现
vector twoSum(vector& nums, int target) {
vector result;
map<int,int>mp;//value->index的映射
//存入哈希表
for(int i=0;i<nums.size();i++){
mp[nums[i]]=i;
}
//在哈希表中查找值
for(int i=0;i<nums.size();i++){
int another=target-nums[i];
map<int,int>::iterator it=mp.find(another);//O(logn)
if(it!=mp.end()&&it->second!=i){
result.push_back(i);
result.push_back(it->second);
return result;
}
}
return result;
}
通过上面的代码可以发现,插入哈希表和查找哈希表分成了两个步骤,其实也可以合并成一个步骤。在插入一个元素之前,先在哈希表中查找,是否存在对应的另一个元素,如果存在,则找到答案,程序退出,否则插入当前元素。这样就不需要判定元素重复的问题。代码如下
vector twoSum(vector& nums, int target) {
vector result;
map<int,int>mp;//value->index的映射
//存入哈希表
for(int i=0;i<nums.size();i++){
//检查当前待插入的元素,对应元素是否已经存在哈希表
int another=target-nums[i];
map<int,int>::iterator it=mp.find(another);//O(logn)
if(it!=mp.end()){
result.push_back(it->second);
result.push_back(i);
return result;
}
else
mp[nums[i]]=i;
}
return result;
}
至此此题结束。
另外如果是查找对应的值相加,可以先排序,再用two-points方法