码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_Search for a Range

时间:2015-05-17 15:20:18      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:search for a range   binary search   

描述:

Given a sorted array of integers, 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].

思路:

1.二分查找,找到value为target的一个元素的位置,找不到返回[-1,-1]

2.假设找到位置,且为index,分别向两边拓展即可。

代码:

 public int[] searchRange(int[] A, int target) {
        int arr[]=new int[2];
        Arrays.fill(arr, -1);
        if(A==null||A.length==0)
        	return arr;
        int len=A.length;
        int start=0,end=len-1;
        int mid=0;
        int index=-1;
        while(start<=end)
        {
        	mid=(start+end)/2;
        	if(A[mid]==target)
        	{
        		index=mid;
        		break;
        	}else if(A[mid]<target)
        		start=mid+1;
        	else 
        		end=mid-1;
        }
        if(index==-1)
        	return arr;
        int i=1,temp=index-i;
        while(temp>=0&&A[temp]==target)
        {
        	i++;
        	temp=index-i;
        }
        arr[0]=index-i+1;
        i=1;
        temp=index+i;
        while(temp<len&&A[temp]==target)
        {
        	i++;
        	temp=index+i;
        }
        arr[1]=index+i-1;
        return arr;
    }


leetcode_Search for a Range

标签:search for a range   binary search   

原文地址:http://blog.csdn.net/mnmlist/article/details/45788751

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!