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):
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