Two Sum
Total Accepted: 14280 Total Submissions: 74978Given 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
C++ Code:
class Solution
{
private:
struct Item
{
Item();
Item(int val, int idx)
{
value = val;
index = idx;
}
int index;
int value;
bool operator < (const Item &a) const
{
return value < a.value;
}
};
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<Item> items;
vector<int> twoNum;
for (int i = 0; i < numbers.size(); ++i)
{
items.push_back(Item(numbers.at(i), i));
}
sort(items.begin(), items.end());
int low = 0, high = items.size() - 1, curSum;
while(low < high)
{
curSum = items.at(low).value + items.at(high).value;
if (curSum > target)
{
--high;
}
else if (curSum < target)
{
++low;
}
else
{
twoNum.push_back(items.at(low).index + 1);
twoNum.push_back(items.at(high).index + 1);
if (twoNum.at(0) > twoNum.at(1))
{
swap(twoNum.at(0), twoNum.at(1));
}
break;
}
}
return twoNum;
}
};