标签:
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]
.
int ReturnArray[2]={-1,-1}; int* searchRange(int A[], int n, int target) { int StartingDex = 0,EndingDex = 0; int i; int IsFoundTarget = 0; int IstheLastElement = 0; int IHalf = (int)(n/2)-1; /* 0 n/2 n-1 */ /* 0 n/2 */ if( IHalf < 0 ) IHalf = 0; if( target >= A[0] && target <= A[IHalf] ) { for( i = 0; i <= IHalf; i++) { if( target == A[i] && IsFoundTarget == 0 ) { /* found the target */ IsFoundTarget=1; StartingDex = i; EndingDex = StartingDex; continue; } else { if( target == A[i] ) { EndingDex = i; } continue; } } } /* n/2 n-1 */ if( target >= A[IHalf] && target <=A[n-1] ) { for( i = IHalf; i <= n-1; i++) { if( i == n-1 ) IstheLastElement = 1; if( target == A[i] ) { if( IsFoundTarget == 0 )/* StartingDex not found before */ { IsFoundTarget = 1; StartingDex = i; } if( IsFoundTarget != 0 || IstheLastElement != 0 ) { EndingDex = i; continue; } } } } if( IsFoundTarget == 0 ) { StartingDex = EndingDex = -1; } ReturnArray[0] = StartingDex; ReturnArray[1] = EndingDex; return ReturnArray; }
Result :
标签:
原文地址:http://blog.csdn.net/oimchuan/article/details/44195141