二分查找之Search for a Range

二分查找经常在有序数列中查找某个特定的位置。

因此使用二分查找应满足以下两个条件:

1:存储在数组中

2:有序排列

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

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

针对这道题,我的想法是先用二分查找的方法找到target,如果target不存在,我就直接返回-1,-1

如果找到target之后然后再确定range,但是这样会出现运行时间超过限制的问题。我的代码附在下面。

public int[] searchRange(int[] A, int target) {
        int count1 = 0;
        int count2 = 0;
        int length = A.length;
        int[] result = {-1,-1};
        int low = 0;
        int high = length - 1;
        int mid = (low+high)/2;
        if(A==null||length==0){
        	return result;
        }
        while(A[mid]!=target){
        	if(A[mid]<target){
        		low = mid + 1;
        		mid = (low+high)/2;
        	}
        	else{
        		high = mid - 1;
        		mid = (low+high)/2;
        	}
        	if(low == high){
            	return result;
            }
        }
        for(low = mid-1;low>0;low--){
        	if(A[low]!= target){
        		count1 = low;
        		break;
        	}
        }
        for(high = mid + 1;high<length;high++){
        	if(A[high]!= target){
        		count2 = high;
        		break;
        	}
        }
        
        result[0] = count1+1;
        result[1] = count2-1;
        return result;
    }

  不知道是不是逻辑有问题,看了别人的代码之后懒得调了,它不仅仅在查找的时候使用二分法,在后面确定range的时候仍然使用二分法

下面附上别人的代码:

public static int[] searchRange(int[] A, int target) {
        
        int[] res = { -1, -1 };
		if (A == null || A.length == 0)
			return res;

		// first iteration, find target wherever it is
		int low = 0;
		int high = A.length - 1;
		int pos = 0;
		while (low <= high) {
			int mid = (low + high) / 2;
			pos = mid;
			if (A[mid] > target)
				high = mid - 1;
			else if (A[mid] < target)
				low = mid + 1;
			else {
				res[0] = pos;
				res[1] = pos;
				break;
			}
		}

		if (A[pos] != target)
			return res;

		// second iteration, find the right boundary of this target
		int newlow = pos;
		int newhigh = A.length - 1;
		while (newlow <= newhigh) {
			int newmid = (newlow + newhigh) / 2;
			if (A[newmid] == target)
				newlow = newmid + 1;
			else
				newhigh = newmid - 1;
		}
		res[1] = newhigh;

		// third iteration, find the left boundary of this target
		newlow = 0;
		newhigh = pos;
		while (newlow <= newhigh) {
			int newmid = (newlow + newhigh) / 2;
			if (A[newmid] == target)
				newhigh = newmid - 1;
			else
				newlow = newmid+1;
		}
		res[0] = newlow;

		return res;
    }

  我觉得一定是我二分比较那里while(low<=high)那里出错了,但是我的想法是如果在A【mid】!=target的情况下是我依次判断每一个mid的值是否是和target相等。如果到最后仍然不相等说明要查找的元素根本不在,哦,问题来了,这样就没有终止了。哦哦哦。

所以说我的逻辑是有问题的。

posted @ 2015-04-08 15:09  niuer++  阅读(223)  评论(0编辑  收藏  举报