美文网首页
34. Search for a Range(二分查找)

34. Search for a Range(二分查找)

作者: 飞飞廉 | 来源:发表于2017-12-02 14:47 被阅读0次

    leetcode 34 Search for a Range

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

    思路:

    要求复杂度是logn,所以采用二分查找,先找到目标值,由于是有序的,再向左和向右查找找到起始和终止的index;

    var searchRange = function(nums, target) {
        var res=[];
        var l=0;
        var r=nums.length-1;
        while(l<=r){
            var m=Math.floor((l+r)/2);
            if(nums[m]<target){
                l=m+1;
            }else if(nums[m]>target){
                r=m-1;
            }else{
                var left=m;
                var right=m;
                while(left>0 && nums[left-1]===nums[m]) --left;
                while(right<nums.length-1 && nums[right+1]===nums[m]) ++right;
                return [left,right];
            }
        }
        return [-1,-1];
    };
    

    相关文章

      网友评论

          本文标题:34. Search for a Range(二分查找)

          本文链接:https://www.haomeiwen.com/subject/ivynbxtx.html