34. Find the Element in Sorted Array
Question
Given an array of integers
numssorted in non-decreasing order, find the starting and ending position of a giventargetvalue.If
targetis not found in the array, return[-1, -1].You must write an algorithm with
O(log n)runtime complexity.
Solution
二分搜索,首先搜索target。如果搜索到结果为负数,则返回[-1, -1]。
如果搜索到target,则记录index。
然后从index向两边搜索,直到找到界限并返回。
Code
1 | class Solution { |
34. Find the Element in Sorted Array
https://xuanhe95.github.io/2022/07/24/34-Find-the-Element-in-Sorted-Array/
