赞
踩
34. 在排序数组中查找元素的第一个和最后一个位置 - 力扣(LeetCode)
给你一个按照非递减顺序排列的整数数组 nums
,和一个目标值 target
。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target
,返回 [-1, -1]
。
你必须设计并实现时间复杂度为 O(log n)
的算法解决此问题。
输入:nums = [5,7,7,8,8,10]
, target = 8
输出:[3,4]
输入:nums = [5,7,7,8,8,10]
, target = 6
输出:[-1,-1]
输入:nums = [], target = 0 输出:[-1,-1]
0 <= nums.length <= 105
-1e9 <= nums[i] <= 1e9
nums
是一个非递减数组-1e9 <= target <= 1e9
- class Solution {
- public:
- vector<int> searchRange(vector<int>& nums, int target) {
- int x = target;
-
- //1.查找>=x的最小下标
- //[1] 闭区间[l,r]表示待查找的区间
- int l = 0, r = nums.size()-1;
- while(l <= r){
- int mid = l + (r-l)/2;
- if(nums[mid] < x) l = mid+1;
- else r = mid-1;
- } //出来时 r == l-1
- //[0, l)均<x, ..., (r, n)均>=x
- //r+1 亦为 l,即为所求
- int res_l = l; //r+1;
- if(res_l == nums.size() || nums[res_l]!= x) return {-1, -1};
-
- //2.查找<=x的最大下标
- //[1] 闭区间[l,r]表示待查找的区间
- l = 0, r = nums.size()-1;
- while(l <= r){
- int mid = l + (r-l)/2;
- if(nums[mid] <= x) l = mid+1;
- else r = mid-1;
- } //出来时 r == l-1
- //[0, l)均<=x, ..., (r, n]均>x
- // l-1 亦为 r,即为所求
- int res_r = r;
-
-
- return {res_l, res_r};
-
- }
- };
- class Solution {
- public:
- vector<int> searchRange(vector<int>& nums, int target) {
- int x = target;
-
- //1.查找>=x的最小下标
- //[2] 左闭右开区间[l, r)表示待查找区间
- int l = 0, r = nums.size();
- while(l < r){
- int mid = l + (r-l)/2;
- if(nums[mid] < x) l = mid+1;
- else r = mid;
- } //出来时 l == r
- //[0, l)均<x, ..., [r, n]均>=x
- //r 亦为 l,即为所求
- int res_l = r;
- if(res_l == nums.size() || nums[res_l] != x) return {-1, -1};
-
- //2.查找<=x的最大下标
- //[2] 左闭右开区间[l, r)表示待查找区间
- l = 0, r = nums.size();
- while(l < r){
- int mid = l + (r-l)/2;
- if(nums[mid] <= x) l = mid+1;
- else r = mid;
- } //出来时 l == r
- //[0, l)均<=x, ..., [r, n]均>x
- //l-1 即为所求
- int res_r = l-1;
-
- return {res_l, res_r};
- }
- };
- class Solution {
- public:
- vector<int> searchRange(vector<int>& nums, int target) {
- int x = target;
-
- //1.查找>=x的最小下标
- //[3] 开区间(l, r)表示待查找的区间
- int l = -1, r = nums.size();
- while(l < r - 1){
- int mid = l + (r-l)/2;
- if(nums[mid] < x) l = mid;
- else r = mid;
- } // 出来时 l == r-1
- //[0, l]均<x, ..., [r, n)均>=x
- //r 即为所求
- int res_l = r;
- if(res_l == nums.size() || nums[res_l] != x) return {-1, -1};
-
- //2.查找<=x的最大下标
- l = -1, r = nums.size();
- while(l < r - 1){
- int mid = l + (r-l)/2;
- if(nums[mid] <= x) l = mid;
- else r = mid;
- } //出来时 l == r-1
- //[0, l]均<=x, ..., [r, n)均>x
- //l 亦为 r-1, 即为所求
- int res_r = l;
-
- return {res_l, res_r};
- }
- };
重点在于判断区间满足什么性质!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。