LeetCode-Two Sum-找和等于某个数的两个数-二分查找

https://oj.leetcode.com/problems/two-sum/

这道题我的方案是O(nlogn)的,首先将数组和其序号放进pair中,然后排序这个pair数组。

之后就是枚举第一个数,二分查找第二个数。

我使用了lower_bound:

1)可以在pair数组中查找pair,这时只需要随意指定second即可。

2)查找到的结果是第一个大于target的值。

typedef pair<int,int> scpair;
class Solution {
public:
	int n;
	vector <scpair> a;
	vector<int> twoSum(vector<int> &numbers, int target) {
		n=numbers.size();
		a.resize(n);
		for (int i=0;i<n;i++){
			a[i]=scpair(numbers[i],i+1);
		}
		sort(a.begin(),a.end());
		vector <int> res;
		for (int i=0;i<n-1;i++){
			int left=target-a[i].first;
			int p=lower_bound(a.begin()+i+1,a.end(),scpair(left,0))-a.begin();
			if (p<n){
				if (a[p].first!=left){continue;}
				res.push_back(a[i].second);
				res.push_back(a[p].second);
				sort(res.begin(),res.end());
				return res;
			}
		}
		return res;
	}
};

  

posted @ 2014-10-04 15:08  zombies  阅读(213)  评论(0编辑  收藏  举报