Simple O(log n) JAVA Solution


  • 4
    Y
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int left = 0;
            int right = nums.length - 1;
            while(left <= right){
                int mid = left + (right - left) / 2;
                if(nums[mid] == target){
                    if(nums[left] == target && nums[right] == target)
                        return new int[]{left, right};
                    else if(nums[left] != target)
                        left++;
                    else
                        right--;
                }else if(nums[mid] < target)
                    left = mid + 1;
                else 
                    right = mid - 1;
            }
            
            return new int[]{-1, -1};
        }
    }

  • 0
    A

    Nice solution!


Log in to reply
 

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