Search First/Last Position
Search Any Position (LC.457)
Example
Input: [1, 2, 2, 4, 5, 5], target = 2
Return: either 1 or 2
Input: [1, 2, 2, 4, 5, 5], target = 6
Return: -1Analysis
While Loop
public classicBS(int A[], target) {
if (A == null || A.length == 0)
return -1;
int start = 0, mid, end = A.length - 1;
// stop when start and end next to each other
while (start + 1 < end) {
// mid = (start + end) / 2; might overflow
mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] < target) {
// median is less than target, search in the right section
start = mid + 1;
} else {
// median is bigger than target, search in the left section
end = mid - 1;
}
}
// start is next to end now
if (A[start] == target) {
return start;
} else if (A[end] == target) {
return end;
} else {
return -1;
}
}Recursion
Search First Position (LC.14)
Example
Analysis
Code
Search Last Position (LC.458)
Example
Analysis
Code
Conclusion
Last updated