leetcode_34——Search for a Range(二分查找)

Search for a Range

  Total Accepted: 43717 Total Submissions: 158420My Submissions

 

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

 

Hide Tags
  Array Binary Search
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

      这道题直接采用二分查找就可以,只是有一点我没有接着做下去,就是第一次采用二分查找在已排好序的数列中找到那个数,其实还应该接着分别采用二分查找来找

那个两边的端点,但是由于直接已经可以AC了,所以我没有接着做下去了

#include<iostream>

#include<vector>

using namespace std;

vector<int> searchRange(vector<int>& nums, int target) {

	int len=nums.size();

	int i=0;

	int j=len;

	int flag=0;

	int locat;

	while(i!=j)

	{

		int z=(i+j)/2;

		if(nums[z]==target)

		{flag=1;locat=z;break;}



		if(target>nums[z])

			i=z+1;

		else

			j=z;

	}

	vector<int> last_reault;

	if(flag==0)

	{

		last_reault.push_back(-1);

		last_reault.push_back(-1);

	}

	else

	{

		int a=locat,b=locat;

		for(int i=locat;i<len;i++)

			if(nums[i]==target)

				a=i;

		for(int j=locat;j>=0;j--)

			if(nums[j]==target)

				b=j;

		last_reault.push_back(b);

		last_reault.push_back(a);

	}

	return last_reault;

}

int main()

{



}

  

 

你可能感兴趣的:(LeetCode)