Search for a Range

题目地址:
https://leetcode.com/problems/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].

解题思路:
这道题就是做两次二分搜索操作,然后更新输出结果的array。需要注意的是如果没有找到,可以直接返回-1.

代码:

public int[] searchRange(int[] nums, int target) {
    if(nums == null || nums.length == 0){
        return new int[]{-1, -1};
    }
    int start = 0, end = nums.length - 1;
    int[] rst = new int[2];
    while(start + 1 < end){
        int mid = start + (end - start) / 2;
        if(target <= nums[mid]){
            end = mid;
        }
        else{
            start = mid;
        }
    }
    if(nums[start] == target){
        rst[0] = start;
    }
    else if(nums[end] == target){
        rst[0] = end;
    }
    else{
        return new int[]{-1, -1};
    }
    start = 0;
    end = nums.length - 1;
    while(start + 1 < end){
        int mid = start + (end - start) / 2;
        if(target < nums[mid]){
            end = mid;
        }
        else{
            start = mid;
        }
    }
    if(nums[end] == target){
        rst[1] = end;
    }
    else if(nums[start] == target){
        rst[1] = start;
    }
    else {
        return new int[]{-1 , -1};
    }
    return rst;
}








Comments

Popular Posts