34. Search for a Range

Description

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].

Solution

Binary search

注意返回right还是left哦。

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int firstIndex = search(nums, target, true);
        if (firstIndex >= nums.length || nums[firstIndex] != target) {
            return new int[]{-1, -1};
        }
        
        int lastIndex = search(nums, target, false);
        int[] res = new int[2];
        res[0] = firstIndex;
        res[1] = lastIndex;
        return res;
    }
    
    public int search(int[] nums, int target, boolean isFirst) {
        int left = 0;
        int right = nums.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (target > nums[mid] || (target == nums[mid] && !isFirst)) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return isFirst ? left : right;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容