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> findTwo(vector<int> copy, int t)
{
int len = copy.size();
int i = 0, j = len - 1;
vector<int> v;
while(i < j)
{
if(copy[i] + copy[j] == t)
{
v.push_back(copy[i]);
v.push_back(copy[j]);
return v;
}
else if(copy[i] + copy[j] < t)
i++;
else
j--;
}
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> copyNums = nums;
sort(copyNums.begin(), copyNums.end());
vector<int> two = findTwo(copyNums, target);
int index0, index1;
bool flag = false;
for(int i = 0; i < nums.size(); i++)
{
if(two[0] == nums[i] && !flag)
{
index0 = i + 1;
flag = true;
}
if(two[1] == nums[i])
index1 = i + 1;
}
two.pop_back();
two.pop_back();
if(index0 > index1)
{
two.push_back(index1);
two.push_back(index0);
}
else
{
two.push_back(index0);
two.push_back(index1);
}
return two;
}
};
本文介绍了一个算法,用于在给定的整数数组中找到两个元素,它们的和等于特定的目标数。该算法通过排序数组并使用双指针技术来提高效率。
329

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



