A very straight solution


  • 0
    P
            int low = 0, high = nums.length - 1;
            int[] found = { low, high };
            int[] notFound = { -1, -1 };
            while (high - low > 1) {
                int mid = low + (high - low) / 2;
                if (nums[mid] > target) {
                    high = mid;
                } else if (nums[mid] < target) {
                    low = mid;
                } else if (nums[mid] == target) {
                    int i = 0;
                    while (mid - i - 1 >= 0 && nums[mid - i - 1] == target) {
                        i++;
                    }
                    found[0] = mid - i;
                    i = 0;
                    while (mid + i + 1 < nums.length && nums[mid + i + 1] == target) {
                        i++;
                    }
                    found[1] = mid + i;
                    return found;
                }
            }
    
            if (high == low && nums[high] != target) {
                return notFound;
            }
            if (nums[high] == target && nums[low] == target) {
                return found;
            } else if (nums[high] == target) {
                found[0] = high;
            } else if (nums[low] == target) {
                found[1] = low;
            } else {
                return notFound;
            }
            return found;

Log in to reply
 

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