题目链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
题目如下:
class Solution { public int[] searchRange(int[] nums, int target) { int low=0,high=nums.length-1,mid=0; int find_flag=0,i,j; int[] a={-1,-1};//创建要返回的数组,并初始化 while(low<=high){//小——》大,折半查找找到目标值 mid=(low+high)/2; if(nums[mid]>target) high=mid-1; else if(nums[mid]<target) low=mid+1; else if(nums[mid]==target) {find_flag=1;break;} } i=j=mid; if(find_flag==1){//双指针法向外扩 while(i-1>=0&&nums[i-1]==target) i--; a[0]=i; while(j+1<nums.length&&nums[j+1]==target) j++; a[1]=j; } return a; } }