Accepted - Modified Binary search solution (Java)


  • 0
    A

    This solution is a modified form of binary search algorithm. Very easy to understand.

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int len = nums.length;
            int[] output = new int[2];
            if(len == 0){
                output[0] = -1;
                output[1] = -1;
                return output;
            }
            
            if(nums[0] == target){
                output[0] = 0;
            }else{
                output[0] = binarySearchMod(nums, target, true);
            }
            
            if(nums[len-1] == target){
                output[1] = len-1;
            }else{
                output[1] = binarySearchMod(nums, target, false);
            }
            return output;
        }
        
        public int binarySearchMod(int[] nums, int target, boolean isLeft){
            int mid = 0;
            int left = 0;
            int right = nums.length - 1;
            if(isLeft){
                left = 1;
            }else{
                right = nums.length - 2;
            }
            while(left <= right){
                mid = left + (right - left)/2;
                if(nums[mid] < target){
                    left = mid+1;
                }else if(nums[mid] > target){
                    right = mid-1;
                }else{
                    if(isLeft){
                        if(nums[mid-1] < nums[mid]){
                            return mid;
                        }else{
                            right = mid-1;
                        }
                    }else{
                        if(nums[mid+1] > nums[mid]){
                            return mid;
                        }else{
                            left = mid+1;
                        }
                    }
                }
            }
            return -1;
        }
    }
    

Log in to reply
 

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