Practice/Meta/Leetcode 34. Find First and Last Position of Element in Sorted Array
CodingMust
You are given a sorted array of integers arranged in non-decreasing order and a target integer value. Your task is to find the starting and ending positions of the target value within the array.
If the target value appears in the array, return a two-element array containing the first index and last index where the target appears. If the target is not found in the array, return [-1, -1].
Your algorithm must run in O(log n) time complexity, where n is the length of the array.
[start, end] representing the range of indices where the target appears[-1, -1]Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3, 4] Explanation: The number 8 appears at indices 3 and 4.
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1, -1] Explanation: The number 6 does not appear in the array.
Example 3:
Input: nums = [], target = 0 Output: [-1, -1] Explanation: The array is empty, so the target cannot be found.
Example 4:
Input: nums = [1], target = 1 Output: [0, 0] Explanation: The single element matches the target at position 0.