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
return
Solution:
Usually, O(log n) is related to binary search.
binary search multiple times, worst O(N)
Given
[5, 7, 7, 8, 8, 10] and target value 8,return
[3, 4].
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] result = {Integer.MAX_VALUE, Integer.MIN_VALUE};
binarySearch(A, target, 0, A.length-1, result);
if(result[0] == Integer.MAX_VALUE)
result[0] = -1;
if(result[1] == Integer.MIN_VALUE)
result[1] = -1;
return result;
}
public void binarySearch(int[] A, int target, int low, int high, int[] result){
if(low > high) return;
int mid = (low + high) / 2;
if(target == A[mid]){
result[0] = Math.min(result[0], mid);
result[1] = Math.max(result[1], mid);
binarySearch(A, target, low, mid-1, result);
binarySearch(A, target, mid+1, high, result);
}
else if(target > A[mid])
binarySearch(A, target, mid+1, high, result);
else if(target < A[mid])
binarySearch(A, target, low, mid-1, result);
}
}
No comments:
Post a Comment