Two Sum
My Submissions
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:
struct Item{
public :
int val;
int idx;
Item (int val,int idx) : val(val), idx (idx) {}
bool operator < ( const Item & rhs )const{
if (this->val == rhs.val)
return (this->idx < rhs.idx);
return (this->val < rhs.val);
}
};
vector<int> twoSum(vector<int> &numbers, int target){
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<Item> vi(numbers.size(), Item(0, 0));
for (int i = 0, sz = numbers.size(); i < sz; ++i) {
vi.at(i) = Item(numbers.at(i), i + 1);
}
sort(vi.begin(), vi.end());
/*for (vector<Item>::iterator it = vi.begin(); it != vi.end(); ++it ) {
cout << it->val << "->" << it->idx << endl;
}*/
int lhs = 0, rhs = vi.size() - 1;
vector<int> res;
while (lhs < rhs) {
if (vi.at(lhs).val + vi.at (rhs).val > target)
--rhs;
else if (vi.at(lhs).val + vi.at (rhs).val < target)
++lhs;
else {
res.push_back(vi.at(lhs).idx);
res.push_back(vi.at(rhs).idx);
break;
}
}
if (res.at(0) > res.at(1))
swap (res.at(0), res.at(1));
return res;
}
};
Two Sum
My SubmissionsGiven 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:
struct Item{
public :
int val;
int idx;
Item (int val,int idx) : val(val), idx (idx) {}
bool operator < ( const Item & rhs )const{
if (this->val == rhs.val)
return (this->idx < rhs.idx);
return (this->val < rhs.val);
}
};
vector<int> twoSum(vector<int> &numbers, int target){
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<Item> vi(numbers.size(), Item(0, 0));
for (int i = 0, sz = numbers.size(); i < sz; ++i) {
vi.at(i) = Item(numbers.at(i), i + 1);
}
sort(vi.begin(), vi.end());
/*for (vector<Item>::iterator it = vi.begin(); it != vi.end(); ++it ) {
cout << it->val << "->" << it->idx << endl;
}*/
int lhs = 0, rhs = vi.size() - 1;
vector<int> res;
while (lhs < rhs) {
if (vi.at(lhs).val + vi.at (rhs).val > target)
--rhs;
else if (vi.at(lhs).val + vi.at (rhs).val < target)
++lhs;
else {
res.push_back(vi.at(lhs).idx);
res.push_back(vi.at(rhs).idx);
break;
}
}
if (res.at(0) > res.at(1))
swap (res.at(0), res.at(1));
return res;
}
};