class Solution {
public :
int search ( vector< int > & nums, int target) {
int length= nums. size ( ) ;
int x= 0 ;
if ( length== 0 || target< nums[ 0 ] || target> nums[ length- 1 ] )
return 0 ;
x= binarysearch ( nums, target, 0 , length- 1 ) ;
if ( nums[ x] == target) {
int l= x, r= x;
while ( l>= 0 && nums[ l] == target) {
l-- ;
}
while ( r< length && nums[ r] == target) {
r++ ;
}
return r- l- 1 ;
}
else
return x;
}
int binarysearch ( vector< int > & nums, int target, int l, int r) {
if ( l== r) {
if ( nums[ l] == target)
return l;
else
return 0 ;
}
int mid= 0 ;
mid= l+ ( r- l) / 2 ;
if ( nums[ mid] < target)
return binarysearch ( nums, target, mid+ 1 , r) ;
else if ( nums[ mid] > target)
return binarysearch ( nums, target, l, mid- 1 ) ;
else
return mid;
}
} ;
class Solution {
public :
int search ( vector< int > & nums, int target) {
int length= nums. size ( ) ;
if ( length== 0 || target< nums[ 0 ] || target> nums[ length- 1 ] )
return 0 ;
int l= 0 , r= length- 1 ;
int mid;
while ( l<= r) {
mid= l+ ( r- l) / 2 ;
if ( target< nums[ mid] )
r= mid- 1 ;
else if ( target> nums[ mid] )
l= mid+ 1 ;
else
break ;
}
if ( nums[ mid] == target) {
l= mid;
r= mid;
while ( l>= 0 && nums[ l] == target)
l-- ;
while ( r< length && nums[ r] == target)
r++ ;
return r- l- 1 ;
}
return 0 ;
}
} ;