Search for a Range

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].

此題在何海濤的書第38題。利用二分法,倆次。分別找左右索引地址。如果只用一次二分,利用一步一步移動尋找,在全爲target時時間複雜度爲o(n)!

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int find_right(int A[], int n, int target);
int find_left(int A[], int n, int target);
vector<int> searchRange(int A[], int n, int target) ;

int main()
{
	int A[] = {5, 8, 8, 8, 8, 10} ;
	vector<int> res = searchRange(A,6,6);
	cout<<res[0]<<endl;
	cout<<res[1]<<endl;

	return 0;
}

vector<int> searchRange(int A[], int n, int target) 
{
	vector<int> pos(2);
	pos[0] = find_left(A,n,target);
	pos[1] = find_right(A,n,target);	
	
	return pos;
}

int find_left(int A[], int n, int target)
{
	if(n <= 0)return -1;
	
	int right = n-1;
	int left = 0;
	int mid;

	while(left <= right)
	{
		mid = (left + right)/2;

		if (A[mid] == target)
		{
			if(mid >= 1 && A[mid-1] == target)
			{
				right = mid -1;
			}
			else
			{
				return mid;
			}
		}
		else if(A[mid] > target)
		{
			right = mid -1;
		}
		else
		{
			left = mid + 1;
		}
	}
	return -1;
}

int find_right(int A[], int n, int target)
{
	if(n <= 0)return -1;

	int right = n-1;
	int left = 0;
	int mid;

	while(left <= right)
	{
		mid = (left + right)/2;

		if (A[mid] == target)
		{
			if(mid < n-1 && A[mid+1] == target)
			{
				left = mid +1;
			}
			else
			{
				return mid;
			}
		}
		else if(A[mid] > target)
		{
			right = mid -1;
		}
		else
		{
			left = mid + 1;
		}
	}
	return -1;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章