Search for a Range

题目
Given an array of integers nums 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].

答案

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

推荐阅读更多精彩内容