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
typedef struct node {
int index;
int val;
node(){}
node(int i, int v): index(i), val(v) {}
bool operator<(const node& n) const { //重载 < 得 加限制符 const
return val < n.val;
}
} Node;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = numbers.size();
vector<Node> ret(len);
for (int i = 0; i < len; ++i) {
ret[i] = Node(i+1, numbers[i]);
}
sort(ret.begin(), ret.end());
int low = 0;
int high = len - 1;
while (low < high) {
if (ret[low].val + ret[high].val == target) {
break;
} else if (ret[low].val + ret[high].val > target) {
--high;
} else {
++low;
}
}
vector<int> res(2, 0);
res[0] = min(ret[high].index, ret[low].index);
res[1] = max(ret[high].index, ret[low].index);
return res;
}
};