LeetCode题解:Search for a Range

Given a sorted array of integers, 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].

题意:给定有序数组,找到目标元素出现的起始位置和终止位置,若没有出现则返回-1,-1

解决思路:二分查找找到目标元素出现位置,然后找目标元素+1的数出现的元素的位置,减去1就是最后的结果了

代码:

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;
    }
}

你可能感兴趣的:(LeetCode题解:Search for a Range)