34. Find First and Last Position of Element in Sorted Array
作者:互联网
My binary search solution:
class Solution { public int[] searchRange(int[] nums, int target) { if(nums==null || nums.length==0) return new int[]{-1,-1}; int l =0, r = nums.length-1; while(l+1<r){ int mid = (l+r)/2; if(nums[mid]>=target) r=mid; else l=mid; } int start = -1; if(nums[l]==target) start=l; else if(nums[r]==target) start=r; if(start!=-1){ int end = start; for(int i=start+1;i<nums.length;i++){ if(nums[i]==target) end++; } return new int[]{start, end}; } else return new int[]{-1,-1}; } }
标签:Last,target,nums,int,mid,Element,start,Sorted,else 来源: https://www.cnblogs.com/feiflytech/p/16168247.html