Java solution : searchLeftMost && searchRightMost


  • 0
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int[] res = new int[]{-1,-1};
            if(nums==null || nums.length==0) return res;
            int left = searchLeftMost(nums,target);
            if(nums[left]!=target)
                return res;
            int right = searchRightMost(nums,target);
            res[0]=left;
            res[1]=right;
            return res;
        }
        
        private int searchLeftMost(int[] nums, int target){
            int low=0,high=nums.length-1;
            while(low<high){
                int mid=low+high>>>1;
                if(target<=nums[mid])
                    high=mid;
                else
                    low=mid+1;
            }
            return low;
        }
        
        private int searchRightMost(int[] nums, int target){
            int low=0,high=nums.length-1;
            while(low<high){
                int mid=low+high+1>>>1;
                if(target>=nums[mid])
                    low=mid;
                else
                    high=mid-1;
            }
            return low;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.