Search for a Range Total Accepted: 36248 Total Submissions: 130885
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O(log n).
if The target is not a found in the array, Return [-1,-1] .
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
Return [3, 4] .
MySolution:
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++) {i F (target = = A[i] && Isfoundtarget = = 0) {/* found the target */Isfoun Dtarget=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:
Submission result:accepted
Search for a Range