Here's my Java code.Is there any optimation?


  • 0
    R
    public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = binarySearch(nums, target);
        
        if(left == nums.length || nums[left] != target){
            return new int[]{-1, -1};
        }
        
        return new int[]{left, binarySearch(nums, target + 1) - 1};
    }
    
    private int binarySearch(int[] nums, int target){
        int count = nums.length;
        int step = 0;
        int left = 0;
        int mid = 0;
        
        while(count > 0){
            step = count >> 1;
            mid = left + step;
            
            if(nums[mid] < target){
                left = mid + 1;
                count -= (step + 1);
            }else{
                count = step;
            }
        }
        
        return left;
    }
    

    }


Log in to reply
 

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