1. Sort : O(n*lgn)
2. two points search from both ends to middle : O(n)
1 struct Node 2 { 3 int val; 4 int index; 5 Node(){} 6 Node(int v, int idx):val(v), index(idx){} 7 }; 8 9 bool compare(const Node &lhs, const Node &rhs) 10 { 11 return lhs.val < rhs.val; 12 } 13 14 class Solution { 15 public: 16 vector<int> twoSum(vector<int> &numbers, int target) { 17 // Start typing your C/C++ solution below 18 // DO NOT write int main() function 19 vector<Node> a; 20 for(int i = 0; i < numbers.size(); i++) 21 a.push_back(Node(numbers[i], i + 1)); 22 sort(a.begin(), a.end(), compare); 23 24 int i = 0; 25 int j = numbers.size() - 1; 26 while(i < j) 27 { 28 int sum = a[i].val + a[j].val; 29 if (sum == target) 30 { 31 vector<int> ret; 32 int minIndex = min(a[i].index, a[j].index); 33 int maxIndex = max(a[i].index, a[j].index); 34 ret.push_back(minIndex); 35 ret.push_back(maxIndex); 36 return ret; 37 } 38 else if (sum < target) 39 i++; 40 else 41 j--; 42 } 43 } 44 };