LeetCode 34. 搜索范围(search for a range)

题目描述

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-1, -1]

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]

解题思路

利用二分查找的思想,分别找到数组中target出现的首位置和末位置,其中找首位置的步骤如下:

  • 若数组中点值小于target,继续在中点值之后的数组查找
  • 若数组中点值大于或等于target,说明前面数组中还可能有target,继续在中点值之前的数组查找
  • 最后当首位置大于末位置时,首位置即为数组中第一个大于或等于target的值
  • 若首位置上的数与target相等,则返回该位置,否则返回-1

同理可得到找末位置的步骤。

代码

 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         if(nums.empty())
 5             return {-1,-1};
 6         int first=findFirst(nums,target);
 7         int last=findLast(nums,target);
 8         return {first,last};
 9     }
10     int findFirst(vector<int>& nums, int target){
11         int f=0,l=nums.size()-1;
12         while(f<=l){
13             int m=(f+l)/2;
14             if(nums[m]<target)
15                 f=m+1;
16             else
17                 l=m-1;
18         }
19         if(f<nums.size()&&nums[f]==target)
20             return f;
21         return -1;
22     }
23     int findLast(vector<int>& nums, int target){
24         int f=0,l=nums.size()-1;
25         while(f<=l){
26             int m=(f+l)/2;
27             if(nums[m]<=target)
28                 f=m+1;
29             else
30                 l=m-1;
31         }
32         if(l>=0&&nums[l]==target)
33             return l;
34         return -1;
35     }
36 };

猜你喜欢

转载自www.cnblogs.com/wmx24/p/9010148.html