LeetCode 34. Search for a Range (找到一个范围)

时间:2023-03-08 18:49:07

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].


题目标签:Array

  这道题目给了我们一个 有序序列,其中是有重复的,让我们找到target的范围,如果没有target,就返回 [-1,-1]。既然规定我们用O(log n),那么肯定是利用binary search。问题是,用binary search 是可以找到target, 但是这里需要找到一个范围,中间可能有很多个重复的target。我们可以用两次binary search, 第一次就找到第一个target, 第二次找到最后一个target,这样就可以返回target的范围了。

  怎么来找到第一个target呢,分析一下,如果中间的数字 大于 target, 那么说明target 还在更左边, 我们要把 right = mid - 1。如果中间数字 小于 target, 说明target 在更右边,要把 left = mid + 1。 到这里为止,都是普通的二分法,那么如果中间的数字是等于 target 的呢,因为我们要找到第一个target的位置,所以,就算找到了target, 我们也要向左边移动,因此,要把这个等于的情况加入 大于里面去。因为它们两种情况都是向左边移动。每次找到target 的时候,还需要 记住它的位置,之后一直更新。因为你找到的target 不一定是最左边的,所以要一直更新,最后一次就是最左边的target位置。

  找最后一个target也是同理。

Java Solution:

Runtime beats 79.19%

完成日期:07/14/2017

关键词:Array

关键点:用两次二分法,第一次来找最左边的target,第二次来找最右边的target

 public class Solution
{
public int[] searchRange(int[] nums, int target)
{
int[] res = {-1, -1}; // first binary search to find the first target
int left = 0;
int right = nums.length - 1; while(left <= right)
{
int mid = left + (right - left) / 2;
if(nums[mid] >= target) // if mid one is greater or equal to target
right = mid - 1; // move to left half
else // if mid one is less than target
left = mid + 1; // move to right half if(nums[mid] == target) // update index
res[0] = mid;
} // second binary search to find the last target
right = nums.length - 1; while(left <= right)
{
int mid = left + (right - left) / 2;
if(nums[mid] <= target)
left = mid + 1;
else
right = mid - 1; if(nums[mid] == target)
res[1] = mid;
} return res;
}
}

参考资料:

https://leetcode.com/problems/search-for-a-range/#/discuss

LeetCode 算法题目列表 - LeetCode Algorithms Questions List