二分模板
using namespace std; //二分模板 class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ans={-1,-1}; int n = nums.size(); if(n==0) return ans; //闭区间 int l = 0; int r = n-1; //找最左边 while(l <= r){ int mid = l+(r-l)/2; if(nums[mid] < target) l = mid+1; else if( target < nums[mid]) r = mid-1; else r = mid-1; } if(!(l >= n || nums[l]!=target)) ans[0] = l; l = 0; r = n-1; //找右边 while(l<=r){ int mid = l+(r-l)/2; if(nums[mid] < target) l = mid+1; else if( target < nums[mid]) r = mid-1; else l = mid+1; } if(!(r<0 || nums[r]!=target)) ans[1] = r; //找目标值 l =0; r = n-1; int ret =-1; while(l<=r){ int mid = l+(r-l)/2; if(nums[mid] < target) l = mid+1; else if( target < nums[mid]) r = mid-1; else { ret = mid; break; } } } };