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

解题分析:

对数组区间进行二分查找,如果mid大于target,那么在mid的左边区间进行查找;如果mid小于target,那么在mid的右边区间进行查找;如果mid等于target,有可能这个位置不是边界,向左夹逼,找到第一个等于target值的位置,向右夹逼,找到最后一个等于target值的位置。将这两个位置放入vector中,进行返回。

class Solution {
public:
	vector<int> searchRange(int A[], int n, int target) {
		vector<int> res;
		if(A == NULL || n < 0)
			return res;
		int low = 0,high = n-1,mid;
		int start = -1;
		int end = -1;
		while(low <= high)
		{
			mid = (low+high)/2;
			if(A[mid] > target)
				high = mid-1;
			else if(A[mid] < target)
				low = mid + 1;
			else //A[mid] == target
			{
				int index = mid;
				//向左夹逼
				while(index >= 0 && A[index] == target)
					index--;
				start = index + 1; //记录左边界
				index = mid;
				//向右夹逼
				while(index < n && A[index] == target)
					index++;
				end = index - 1; //记录右边界
				break;
			}
		}
		res.push_back(start);
		res.push_back(end);
		return res;
	}
};



猜你喜欢

转载自blog.csdn.net/qiana_/article/details/80937904