Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in non-decreasing order and a target integer target, find the starting and ending position of a given target value in the array. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
[ [ 5, 7, 7, 8, 8, 10 ], 8 ]
Explanation. The target value 8 occurs at indices 3 and 4.
[ [ 5, 7, 7, 8, 8, 10 ], 6 ]
Explanation. The target value 6 does not appear in the input array, thus the output is [-1, -1].
[ [], 0 ]
Explanation. The input array is empty, therefore, no target can be found.
[ [ 2, 2 ], 2 ]
Explanation. The target value 2 occurs in all the indices of the array, from 0 to 1.
Follow-up: How would you adapt your solution if the input numbers were not sorted?
1. The number of elements in the array is between 1 and 10000. 2. The values of each element in the array range from -10^9 to 10^9. 3. The array `nums` is always sorted in non-decreasing order. 4. The value `target` will range from -10^9 to 10^9.
- Views
- 2