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
Understand the problem:Given
[5, 7, 7, 8, 8, 10]
and target value 8,return
[3, 4]
.The problem gives a sorted array of integers, find the starting and ending position of a given target value. It requires the time complexity as O(logn), which indicates to use binary search. If not found, return [-1, -1].
Solution:
Since the problem asks for O(logn) solution, we can solve this problem by using the binary search for the first and last index of the target.
Code (Java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | public class Solution { public int [] searchRange( int [] A, int target) { if (A == null || A.length == 0 ) { int [] result = {- 1 , - 1 }; return result; } int [] result = new int [ 2 ]; // Find the first index of the target value result[ 0 ] = binarySearchFirstIndex(A, target); if (result[ 0 ] == - 1 ) { result[ 1 ] = - 1 ; return result; } // Find the last index of the target value result[ 1 ] = binarySearchLastIndex(A, target); return result; } private int binarySearchFirstIndex( int [] A, int target) { int lo = 0 ; int hi = A.length - 1 ; while (lo + 1 < hi) { int mid = lo + (hi - lo) / 2 ; if (A[mid] == target) { hi = mid; } else if (A[mid] > target) { hi = mid; } else { lo = mid; } } if (A[lo] == target) { return lo; } if (A[hi] == target) { return hi; } return - 1 ; } private int binarySearchLastIndex( int [] A, int target) { int lo = 0 ; int hi = A.length - 1 ; while (lo + 1 < hi) { int mid = lo + (hi - lo) / 2 ; if (A[mid] == target) { lo = mid; } else if (A[mid] > target) { hi = mid; } else { lo = mid; } } if (A[hi] == target) { return hi; } if (A[lo] == target) { return lo; } return - 1 ; } } |
No comments:
Post a Comment