标签:c++ leetcode binary search array

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].
//vs2012测试代码
//Binary Search
//we must know how to process the 3 cases below:
//1.how to find the right most target
//2.how to find the left most target
//3.how to find the insert position
#include<iostream>
#include<vector>
using namespace std;
#define N 6
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> ans(2);
if(n==0)
return vector<int>( 2,-1 );
int left = 0 , right = n-1;
while( left<=right )
{
int mid = left + (right-left)/2;
if( A[mid] >= target) //find the left most target
right = mid-1;
else if (A[mid] < target)
left = mid+1;
}
int target_left = left;
left=0 , right=n-1;
while( left<=right )
{
int mid = left + (right-left)/2;
if(A[mid] <= target) //find the right most target
left = mid +1;
else if ( A[mid] > target)
right = mid -1;
}
int target_right = right;
if( A[target_left]!=target || A[target_right]!=target)
return vector<int>( 2,-1 );
ans[0] = target_left;
ans[1] = target_right;
return ans;
}
};
int main()
{
int a,target;
int A[N];
vector<int> ans(2);
for(int i=0; i<N; i++)
{
cin>>a;
A[i]=a;
}
cin>>target;
Solution lin;
ans = lin.searchRange( A,N,target);
for(int i=0; i<2; i++)
cout<<ans[i];
cout<<endl;
}
//方法一:自测Accepted
//Binary Search
//we must know how to process the 3 cases below:
//1.how to find the right most target
//2.how to find the left most target
//3.how to find the insert position
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> ans(2);
if(n==0)
return vector<int>( 2,-1 );
int left = 0 , right = n-1;
while( left<=right )
{
int mid = left + (right-left)/2;
if( A[mid] >= target) //find the left most target
right = mid-1;
else if (A[mid] < target)
left = mid+1;
}
int target_left = left;
left=0 , right=n-1;
while( left<=right )
{
int mid = left + (right-left)/2;
if(A[mid] <= target) //find the right most target
left = mid +1;
else if ( A[mid] > target)
right = mid -1;
}
int target_right = right;
if( A[target_left]!=target || A[target_right]!=target)
return vector<int>( 2,-1 );
ans[0] = target_left;
ans[1] = target_right;
return ans;
}
};
leetcode_34_Search for a Range
标签:c++ leetcode binary search array
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43635879