Short solution, 1 binary search


  • 0
    N

    The idea I had was to go through and do binary search as usual. The moment we got a binary search, we can search from there to quickly the two ends where the range starts and end.

    Worst case if the whole array is the target, then we actually went through O(n) instead of O(lgn).

    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int i = 0;
            int j = nums.length-1;
            int mid = i + (j-i) / 2;
            
            while(i < j) {
                if(nums[mid] < target) i = mid+1;
                else if(nums[mid] > target) j = mid-1;
                else {
                    i = mid;
                    j = mid;
                    while(i-1 >= 0 && nums[i-1] == target) i--;
                    while(j+1 <= nums.length-1 && nums[j+1] == target) j++;
                    break;
                }
                
                mid = i + (j-i) / 2;
            }
            if(nums[i] != target || nums[j] != target) return new int[]{-1, -1};
            else return new int[]{i, j};
        }
    }
    

Log in to reply
 

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