LeetCode 1. Two Sum
https://leetcode.com/problems/two-sum/
先排序,有序后枚举a,二分查找b,因为必然有解,直接找到就return。
class Solution { public: struct node { int num; int ord; }; static bool cmp(node a,node b) { return a.num<b.num; } int bins(int l,int r,vector<node>& temp,int key) { while(l<=r) { int mid=(l+r)>>1; if(temp[mid].num==key) return mid; if(temp[mid].num>key) r=mid-1; if(temp[mid].num<key) l=mid+1; } return -1; } vector<int> twoSum(vector<int>& nums, int target) { vector<int> ans; vector<node> temp; for(int i=0;i<nums.size();i++) temp.push_back((node){nums[i],i}); sort(temp.begin(),temp.end(),cmp); for(int i=0;i<temp.size();i++) { int pos=bins(i+1,temp.size()-1,temp,target-temp[i].num); if(pos==-1) continue; else { ans.push_back(temp[i].ord),ans.push_back(temp[pos].ord); return ans; } } return ans; } };