Problem
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return [-1, -1].
Example
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
首先,建立二元结果数组res,起点start,终点end。
二分法求左边界:
当中点小于target,start移向中点,否则end移向中点;
先判断起点,再判断终点是否等于target,如果是,赋值给res[0]。
二分法求右边界:
当中点大于target,end移向中点,否则start移向中点;
先判断终点,再判断起点是否等于target,如果是,赋值给res[1]
本文介绍了一种使用二分查找法在已排序数组中精确找到特定目标值起始与结束位置的方法。通过两次运用二分查找,分别确定目标值的左边界和右边界,实现了高效搜索。
1023

被折叠的 条评论
为什么被折叠?



