题目来源:
leetcode题目,网址:34. 在排序数组中查找元素的第一个和最后一个位置 - 力扣(LeetCode)
解题思路:
进行两次二分查找即可。
解题代码:
class Solution {
public:vector<int> searchRange(vector<int>& nums, int target) {vector<int> res{-1,-1};if(nums.size()==0){return res;}res[0]=findFirst(nums,target);if(res[0]==-1){return res;}cout<<res[0]<<endl;res[1]=findLast(nums,target,res[0]);return res;}int findLast(vector<int>& nums,int target,int left){if(nums[nums.size()-1]==target){return nums.size()-1;}int right=nums.size()-2;while(left<=right){int mid=left+(right-left)/2;if(nums[mid]==target){if(nums[mid+1]>target){return mid;}else{left=mid+1;}}else if(nums[mid]>target){right=mid-1;}else{left=mid+1;}}return -1;}int findFirst(vector<int>& nums,int target){if(nums[0]==target){return 0;}int left=1;int right=nums.size()-1;while(left<=right){int mid=left+(right-left)/2;if(nums[mid]==target){if(nums[mid-1]<target){return mid;}else{right=mid-1;}}else if(nums[mid]>target){right=mid-1;}else{left=mid+1;}}return -1;}
};
总结:
官方题解也是两次二分。