- Create a new array
arr
of size 2 to store the start and end indices of the target element in the sorted arraynums
. - Call the
firstIndex()
function to find the start index of the target element in the sorted array. - Call the
lastIndex()
function to find the end index of the target element in the sorted array. - Return the array
arr
.
The firstIndex()
and lastIndex()
functions work in a similar way. They both use binary search to find the start and end indices of the target element in the sorted array, respectively.
The firstIndex()
function works as follows:
- Initialize two pointers,
s
ande
, to the start and end indices of the sorted array, respectively. - While
s
is less than or equal toe
:- Calculate the middle index
mid
ass + (e - s) / 2
. - If the element at the middle index is greater than or equal to the target element, then set the end index
e
tomid - 1
. - Otherwise, set the start index
s
tomid + 1
. - If the element at the middle index is equal to the target element, then set the start index
s
tomid
.
- Calculate the middle index
- Return the start index
s
.
The lastIndex()
function works in a similar way, except that it sets the end index e
to mid + 1
if the element at the middle index is less than or equal to the target element.
Example:
Consider the following sorted array nums
and the target element target = 5
:
nums = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9]
The firstIndex()
function will return the index 3
, which is the start index of the target element in the sorted array.
The lastIndex()
function will return the index 5
, which is the end index of the target element in the sorted array.
Therefore, the searchRange()
function will return the array [3, 5]
.