这个是用递归的方式写的,非递归也可以写。
注意判断的时候可能出现数组越界的问题,所以要判断mid - 1 < 0和mid + 1 >= nums.size(),即数组的头和数组的尾
如果不判断[1],1这种就会报错
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> result; int first = find_first(nums,target,0,nums.size() - 1); int last = find_last(nums,target,0,nums.size() - 1); if(first != -1 && last != -1){ result.push_back(first); result.push_back(last); } else{ result.push_back(-1); result.push_back(-1); } return result; } int find_first(vector<int>& nums,int target,int start,int end){ if(start > end) return -1; int mid = (start + end)/2; if(nums[mid] < target) return find_first(nums,target,mid+1,end); else if(nums[mid] > target) return find_first(nums,target,start,mid-1); else{ if(mid - 1 < 0 || nums[mid - 1] != target) return mid; else return find_first(nums,target,start,mid-1); } } int find_last(vector<int>& nums,int target,int start,int end){ if(start > end) return -1; int mid = (start + end)/2; if(nums[mid] < target) return find_last(nums,target,mid+1,end); else if(nums[mid] > target) return find_last(nums,target,start,mid-1); else{ if(mid + 1 >= nums.size() || nums[mid + 1] != target) return mid; else return find_last(nums,target,mid+1,end); } } };