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
We may do as follow :
class solution{
public:
void help(vector<int>& nums,int target,vector<int>& result){
int sum;
int index1;
int index2;
for(int i=0;i<nums.size()-1;i++){
sum=0;
result.push_back(i);
for(int j=i+1;j<nums.size();j++){
sum=nums[i]+nums[j];
if(sum==target){
result.push_back(j);
return;
}
}
result.pop_back();
}
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
help(nums,target,result);
return result;
}
};
However it is time limited, Think about it carefully accepted as follow:
class solution{
public:
void help(vector<int>& nums,int target,vector<int>& result){
unordered_map<int,int> temp;
int sum;
int index1;
int index2;
for(int i=0;i<nums.size();i++){
temp.insert(make_pair(i,nums[i]));
}
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-1;i++){
sum=0;
for(int j=i+1;j<nums.size();j++){
sum=nums[i]+nums[j];
if(sum==target){
for(int k=0;k<nums.size();k++){
if(temp[k]==nums[i]||temp[k]==nums[j]){
index1=k;
break;
}
}
for(int k=index1+1;k<nums.size();k++){
if(temp[k]==nums[j]||temp[k]==nums[i]){
index2=k;
}
}
if(index1<index2){
result.push_back(index1+1);
result.push_back(index2+1);
return;
}
else{
result.push_back(index2+1);
result.push_back(index1+1);
return;
}
}
}
}
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
help(nums,target,result);
return result;
}
};
We can learn from above that sometimes ordered thing better than unordered thing .
Notice: numbers in array may repeat.