Use a unordered map to save all visited number. While scan the array, find out whether target-nums[i] is already visited.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> mp;
vector<int> res;
int n=nums.size();
for(int i=0;i<n;i++)
{
if(mp.find(target-nums[i])!=mp.end())
{
res.push_back(mp[target-nums[i]]+1);
res.push_back(i+1);
return res;
}
mp[nums[i]]=i;
}
}
};