# 【Leetcode】Two Sum

610人阅读 评论(0)

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

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
if(numbers.empty())
return result;
vector<int> backup(numbers);
sort(numbers.begin(),numbers.end());
getIndex(result,numbers,target);
int index1,index2;
bool finding=true;
for(int i=0;i<backup.size();i++)
{
if(backup[i]==result[0]&&finding)
{
index1=i+1;
finding=false;
continue;
}
if(backup[i]==result[1])
index2=i+1;
}
result.clear();
result.push_back(index1);
result.push_back(index2);
sort(result.begin(),result.end());
return result;
}

void getIndex(vector<int> &result,vector<int> &numbers,int target)
{
for(int i=numbers.size()-1;i>=0;i--)
{
if(target>numbers[i])
{
int index2=numbers[i];
bool index1=find(numbers,target-numbers[i],0,i-1);
if(index1)
{
result.push_back(target-index2);
result.push_back(index2);
return;
}
else
continue;
}
}
}

bool find(vector<int> &numbers,int target,int start,int end)
{
if(end<start)
return false;
int medium=(start+end)>>1;
if(target==numbers[medium])
return true;
else if(target<numbers[medium])
return find(numbers,target,start,medium-1);
else
return find(numbers,target,medium+1,end);
}

};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：58672次
• 积分：1269
• 等级：
• 排名：千里之外
• 原创：66篇
• 转载：14篇
• 译文：0篇
• 评论：2条
博客专栏
 Leetcode面试题解 文章：31篇 阅读：20803
阅读排行
评论排行
最新评论