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].
思路:
1.从一个数组里找两个数a、b之和等于所给的一个数c,先把数组排序,两个指针一个从前向后,一个从后向前,和大于所给数c则指向结尾的指针向前,小于则指向开头的指针向后,但是要返回a、b的索引,所以排序的时候保存索引,这里把数组和对应索引一对一对保存在pair里在存入vector排序就可以了,pair里第一个是数,第二个是索引,复杂度O(nlogn)就是排序复杂度
2.直接用unsorted_map存储,然后找就好了,unsorted_map查找复杂度O(1),遍历复杂度O(n)
代码:
class Solution {
public:
//1.
struct cmp{
bool operator()( const pair<int,int>&a, const pair<int,int>&b){
return a.first < b.first;
}
};
vector<int> twoSum(vector<int>& nums, int target) {
int length=nums.size();
int left=0,right=length-1;
vector<pair<int,int>>new_nums;
for(int i=0;i<length;++i){
new_nums.push_back({nums[i],i});
}
sort(new_nums.begin(),new_nums.end());
for(int i=0;i<length-1;++i){
if(new_nums[left].first+new_nums[right].first==target){
vector<int>ans;
ans.push_back(new_nums[left].second);
ans.push_back(new_nums[right].second);
return ans;
}else if(new_nums[left].first+new_nums[right].first<target){
left++;
}else {
right--;
}
}
}
//2.
vector<int> twoSum1(vector<int>& nums, int target) {
vector<int>res;
unsorted_map<int,int>m;
for(int i=0;i<nums.size();++i){
m[nums[i]]=i;
}
for(int i=0;i<nums.size();++i){
if(m.count(target-nums[i])&&m[target-nums[i]]!=i){
res.push_back(i);
res.push_back(m[target-nums[i]]);
break;
}
}
return res;
}
//3.
vector<int> twoSum2(vector<int>& nums, int target) {
vector<int>res;
unsorted_map<int,int>m;
for(int i=0;i<nums.size();++i){
if(m.count(target-nums[i])&&m[target-nums[i]]!=i){
res.push_back(i);
res.push_back(m[target-nums[i]]);
break;
}
m[nums[i]]=i;
}
return res;
}
};