34. Search for a Range
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
题意:
给定一个按升序排序的整数数组,查找给定目标值的开始位置和结束位置。算法的运行时复杂性必须是O(log n)。如果数组中找不到目标,则返回[ -1,- 1 ]。
思路:
方法一:
直接利用二分查找,找到指定的元素索引,因为是有序的非递减数组,所以相等的元素一定相邻,直接以此索引为中心,左右扩展,找到元素的起始位置和结束位置。
1 | class Solution { |
方法二:
直接利用C++的STL函数库equal_range(),函数详情equal_range()。
1 | class Solution { |
方法三:
直接利用C++的STL函数库lower_bound() 和upper_bound()函数,函数详情lower_bound和upper_bound()。
1 | class Solution { |
Java Code:
1 | class Solution { |