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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> temp;
temp = numbers;
sort(temp.begin(),temp.end());
int left = 0;
int right = temp.size()-1;
vector<int> result;
while(left<right)
{
if(temp[left]+temp[right]<target)
{
left++;
}
else if(temp[left]+temp[right]>target)
{
right--;
}
else if(temp[left]+temp[right]==target)
{
vector<int>::const_iterator location1 = find(numbers.begin(),numbers.end(),temp[left]);
vector<int>::const_iterator location2 = find(numbers.begin(),numbers.end(),temp[right]);//注意find的用法
result.push_back(min(location1-numbers.begin(),location2-numbers.begin())+1);
if(location1==location2)
{
result.push_back((location2-numbers.begin())+2);
}
else
{
result.push_back(max(location1-numbers.begin(),location2-numbers.begin())+1);
}
return result;
}
}
return result;
}
};
本文介绍了一个算法,用于在给定的整数数组中找到两个元素,它们的和等于特定的目标数。该算法通过排序数组并使用双指针技术来高效地解决问题。
1013

被折叠的 条评论
为什么被折叠?



