Created
August 11, 2014 10:07
-
-
Save egraldlo/013989bd5cac5f5a7360 to your computer and use it in GitHub Desktop.
search for a range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> searchRange(int A[], int n, int target) { | |
vector<int> ret; | |
int point=binarySearch(A,0,n-1,target); | |
if(point==-1){ | |
ret.push_back(-1); | |
ret.push_back(-1); | |
return ret; | |
} | |
while(point>=0){ | |
if(A[point]==target){ | |
point--; | |
continue; | |
} | |
else | |
break; | |
} | |
int first=++point; | |
while(point<=n-1){ | |
if(A[point]==target){ | |
point++; | |
continue; | |
} | |
else | |
break; | |
} | |
int last=--point; | |
ret.push_back(first); | |
ret.push_back(last); | |
return ret; | |
} | |
int binarySearch(int A[], int left, int right, int target){ | |
int middle=left+(right-left)/2; | |
if(left>right) | |
return -1; | |
else{ | |
if(A[middle]==target) | |
return middle; | |
else if(target>A[middle]) | |
return binarySearch(A,middle+1,right,target); | |
else | |
return binarySearch(A,left,middle-1,target); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 38行的二分查找应该像这样求中值,然后判断的条件也改为left>right。 此题主要是在考察二分查找,其余的考点为附带。