Search for a Range(LeetCode)

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

思路:

利用二分查找,先找到左边界,再找到右边界。比较判断是否存在。

class Solution {
public:
	vector<int> searchRange(vector<int>& nums, int target) {
		vector<int > v(2,-1);
		if(nums.empty())
			return v;
		//找到第一次出现的位置
		int n=nums.size();
		int low=0;int high=n-1;
		while(low<=high){
			int mid =low + (high-low)/2;
			if(nums[mid]<target) low=mid+1;
			else high=mid-1;
		}
		//找到最后出现的位置
		int low2=0;int high2=n-1;
		while(low2<=high2){
			int mid2=low + (high2-low2)/2;
			if(nums[mid2]>target) high2=mid2-1;
			else low2=mid2+1;
		}
		if(low<=high2){
			v[0]=low;
			v[1]=high2;
		}
		return v;
	}
};



猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80330696