美文网首页
34. Search for a Range

34. Search for a Range

作者: namelessEcho | 来源:发表于2017-10-03 11:10 被阅读0次

    使用二分找到target后,在两侧分别使用二分找到起点和终点。

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int lo = 0 ;
            int hi = nums.length-1;
            int pos = -1;
            while(lo<=hi)
            {
                 int mid = lo+(hi-lo)/2;
                if(nums[mid]==target)
                {
                    pos=mid;
                    break;
                }
                else if(nums[mid]<target)
                {
                    lo=mid+1;
                }
                else
                    hi=mid-1;
            }
            int[] result = new int[2];
            if(pos==-1)
            {
                result[0]=-1;
                result[1]=-1;
                return result;
            }
             lo = 0;
             hi=pos;
            while(lo<=hi)
            {
               int mid = lo+(hi-lo)/2;
               if(nums[mid]<target)
                {
                    lo=mid+1;
                }
                else
                    hi=mid-1;
            }
            int start =lo;
            
            
             lo = pos;
             hi=nums.length-1;
            while(lo<=hi)
            {
               int mid = lo+(hi-lo)/2;
               if(nums[mid]>target)
                {
                    hi=mid-1;
                }
                else
                    lo=mid+1;
            }
            int end =lo-1;
            
            
            result[0]=start;
            result[1]=end;
            return result;
            
        }
    }
    

    相关文章

      网友评论

          本文标题:34. Search for a Range

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