首页 > 其他 > 详细

Search for a Range--LeetCode

时间:2015-03-30 11:19:00      阅读:138      评论:0      收藏:0      [点我收藏+]

题目:

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路:两次使用二分查找,分别找上限和下限

#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
在一个排好序的序列中找打某个值的第一个位置 和最后一个位置 
*/

pair<int,int> Findvalue(vector<int>& vec,int key)
{
	pair<int,int> pos(-1,-1);
	int mid,begin = 0,end = vec.size();
	
	mid = begin + (end-begin)/2;
	if(vec[mid] == key)
	{
		pos.first = mid;
		pos.second= mid;
	}
		
	int low = mid;
	int high = mid+1;
	
	// 找低地址 
	while(begin<= low)
	{
		mid = begin+(low-begin)/2;
		if(vec[mid] == key)
		{
			if(pos.first == -1 || (pos.first!=-1 && mid < pos.first))
				pos.first = mid;
			low = mid-1;
		}
		else if(vec[mid] > key)
			low = mid-1;
		else
			begin = mid+1;
	}
	
	//找高地址 
	while(high <= end)
	{
		mid = high+ (end-high)/2;
		if(vec[mid] == key)
		{
			if(pos.first == -1 || (pos.first!=-1 && mid >pos.first))
				pos.second =mid;
			high = mid+1;
		}
		else if(vec[mid] > key)
			end = mid-1;
		else
			high = mid+1;
	}
	return pos;
	
} 
int main() 
{
	int array[]={5, 7, 7, 8, 8, 10};
	vector<int> vec(array,array+sizeof(array)/sizeof(int));
	pair<int,int> pos = Findvalue(vec,8);
	cout<<pos.first<<"  "<<pos.second<<endl;
	 
	return 0;
}


Search for a Range--LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/44747545

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!