1 package leetcode; 2 3 public class demo_34 { 4 public int[] searchRange(int[] nums, int target) { 5 int[] s= {-1,-1}; 6 if(nums.length==0) {return s;} 7 int right=nums.length-1; 8 int left=0; 9 int mid=(right+left)/2; 10 //通过二分法来查找target的位置 11 while(left<=right) { 12 mid=(left+right)/2; 13 if(target>nums[mid]) { 14 left=mid+1; 15 } 16 if(target<nums[mid]) { 17 right=mid-1; 18 } 19 if(target==nums[mid]) { 20 left=mid; 21 right=mid; 22 while(left>=0&&nums[left]==target) {left=left-1;} 23 s[0]=left+1; 24 while(right<nums.length&&nums[right]==target) {right=right+1;} 25 s[1]=right-1; 26 break; 27 } 28 } 29 for(int i:s) { 30 System.out.print(i+" "); 31 } 32 return s; 33 } 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 demo_34 d34=new demo_34(); 37 int[] nums= {5,7,7,8,8,10}; 38 d34.searchRange(nums, 8); 39 } 40 41 }