Created
February 19, 2013 01:40
-
-
Save zhoutuo/4982373 to your computer and use it in GitHub Desktop.
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].
This file contains hidden or 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) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
int low = low_bound(A, n, target); | |
int high = high_bound(A, n, target); | |
if(low == -1 xor high == -1) { | |
if(low == -1) { | |
return vector<int>{0, high - 1}; | |
} else { | |
return vector<int>{low + 1, n - 1}; | |
} | |
} else if(low == -1 and high == -1) { | |
if(A[0] == target) { | |
return vector<int>{0, n - 1}; | |
} | |
return vector<int>{-1, -1}; | |
} else { | |
return vector<int>{low + 1, high - 1}; | |
} | |
} | |
int low_bound(int A[], int n, int target) { | |
int low = 0; | |
int high = n; | |
while(low < high) { | |
int mid = low + (high - low) / 2; | |
if(A[mid] >= target) { | |
high = mid; | |
} else { | |
if(mid <= n - 2 && A[mid + 1] == target) { | |
return mid; | |
} else { | |
low = mid + 1; | |
} | |
} | |
} | |
return -1; | |
} | |
int high_bound(int A[], int n, int target) { | |
int low = 0; | |
int high = n; | |
while(low < high) { | |
int mid = low + (high - low) / 2; | |
if(A[mid] <= target) { | |
low = mid + 1; | |
} else { | |
if(mid > 0 && A[mid - 1] == target) { | |
return mid; | |
} else { | |
high = mid; | |
} | |
} | |
} | |
return -1; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment