设为首页 加入收藏

TOP

leetcode_Search for a Range
2015-11-21 01:01:57 来源: 作者: 【 】 浏览:1
Tags:leetcode_Search for Range

描述:

?

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]
  
   =0&&A[temp]==target)
        {
        	i++;
        	temp=index-i;
        }
        arr[0]=index-i+1;
        i=1;
        temp=index+i;
        while(temp
   
    

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj 2356 Find a multiple (鸽巢.. 下一篇leetcode 207: Course Schedule

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: