# two_Sum

unknown
c_cpp
19 days ago
1.8 kB
3
Indexable
Never
```class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
map<int,int> u_map;
for(int i = 0; i < nums.size(); i++)
{
u_map[nums[i]] = (1+i);
}
int index = -1;
for(auto x : u_map)
{
int value = target - x.first;
if(value == x.first)
{
index = x.second-1;
break;
}
if(u_map[value])
return {x.second-1, u_map[value]-1};
}
if(index != -1)
{
for(int i =0; i < index; i++)
{
if(nums[i] == nums[index])
return {i, index};
}
}
return {-1, -1};
}
};

____________________________________________________________

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector <int> two_sum;
for(int i=0;i<nums.size();i++)
two_sum.push_back(nums[i]);
sort(two_sum.begin(),two_sum.end());
int l=0,r=two_sum.size()-1;
while(l<r)
{
if(two_sum[l]+two_sum[r]==target)
{
// cout<<l<<' '<<r<<endl;
l=two_sum[l];
r=two_sum[r];
// cout<<l<<' '<<r<<endl;
break;
}
else if(two_sum[l]+two_sum[r]>target)
r--;
else
l++;
}
int ind1=-1,ind2=-1;
for(int i=0;i<nums.size();i++)
{
if(nums[i]==l&&ind1==-1) {ind1=i; continue;}
if(nums[i]==r){ind2=i;}
}
return {ind1,ind2};
}
};```