LeetCode Java First 400 题解-034

Search for a Range    Medium

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given 
[5, 7, 7, 8, 8, 10] and target value 8,
return 
[3, 4].

public int[] searchRange(int[] nums, int target) {

    int[] ans = { -1, -1 };

    ans[0] = firstPlaceLeft(nums, target);

    ans[1] = firstPlaceRight(nums, target);

    return ans;

}

 

private static int firstPlaceLeft(int[] nums, int target) {

    int l = 0, r = nums.length - 1, mid = 0;

    while (l <= r) {

        mid = (l + r) / 2;

        if (target > nums[mid])

            l = mid + 1;

        else {

            if (nums[mid] == target && (mid == l || (mid > l && nums[mid - 1] != target))) {

                return mid;

            }

            r = mid - 1;

        }

    }

    return -1;

}

 

private static int firstPlaceRight(int[] nums, int target) {

    int l = 0, r = nums.length - 1, mid = 0;

    while (l <= r) {

        mid = (l + r) / 2;

        if (target < nums[mid])

            r = mid - 1;

        else {

            if (nums[mid] == target && (mid == r || (mid < r && nums[mid + 1] != target))) {

                return mid;

            }

            l = mid + 1;

        }

    }

    return -1;

}

思路:使用两个变形的二分查找,分别找第一个、最后一个等于给定数的位置。
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页