class Solution { public: /** * * @param numbers int整型vector * @param target int整型 * @return int整型vector */ vector<int> twoSum(vector<int>& numbers, int target) { // write code here vector<int> copy = numbers; sort(numbers.begin(),numbers.end()); for(int i=0;i<numbers.size();i++){ int index = binaryfind(numbers, target - numbers[i]); // cout<<index<<" "<<i<<" "; if(index!=-1 && index!=i) { // cout<<"jin"; // return {i,index}; vector<int> res; for(int j=0;j<numbers.size();j++) { // for(auto a : res) { // cout<<a<<" "; // } if(copy[j] == numbers[index] || copy[j] ==numbers[i]) { res.emplace_back(j+1); } if(res.size()==2) { return res; } } } } return {}; } int binaryfind(vector<int>& numbers , int target) { // 左闭右开 int left =0; int right = numbers.size(); // 那么结束的条件就是 left=right while(left<right) { int mid = left + (right-left)/2; int value = numbers[mid]; if(target==value){ return mid; } else if(target>value) { left = mid+1; } else if(target<value) { right=mid; } } return -1; } };