leetcode之Search for a 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].

思路:这道题很容易想到的思路是利用二分查找找到target,然后以找到的target为中心向前向后遍历,这种方法由于还需要有一个遍历的过程,所以在最坏情况下的时间复杂度是O(n)。

vector<int> searchRange(int A[], int n, int target) {
        int low = 0;
		int high = n - 1;
		vector<int>v;
		int index = binarySearch(A,low,high,target);
		//printf("%d\n",index);
		if(index == -1){
			v.push_back(-1);
			v.push_back(-1);
			return v;
		}
		low = index;
		high = index;
		while( low >= 0 && A[low] == target )
			low--;
		while(high < n && A[high] == target)
			high++;
		v.push_back(++low);
		v.push_back(--high);
		return v;
		
    }
	int binarySearch(int A[],int low,int high,int target){
		if(low <= high){
			int mid= (low + high)/2;
			if(A[mid] == target)
				return mid;
			if(A[mid] > target)
				return binarySearch(A,low,mid - 1,target);
			else
				return binarySearch(A,mid + 1,high,target);
		}
		else
			return -1;
		
	}
另一种思路是直接利用二分查找寻找target的下限和上限,寻找下限的原则是不错过第一个相等的元素,寻找上限的原则是不错过最后一个相等的元素,这里边有一个问题是mid在取值时更加靠近low,所以寻找上限与寻找下限时指针的移动稍有不同,这点儿需要注意。

vector<int> searchRange(int A[], int n, int target) {
	    int low = 0;
		int high = n - 1;
		//找下限
		vector<int>v(2,-1);
		while(low < high){
		    int mid = (low + high) / 2;
			if(A[mid] < target)  //原则是不能错过最前一个相等元素
				low = mid + 1;
			else
				high = mid;				
		}
		if(A[low] != target)
			return v;
		v[0] = low;
		//找上限
		high = n - 1;      
		while(low < high){  
			int mid = (low + high) / 2;
			if(A[mid] > target)    //原则是不能错过最后一个相等元素
				high = mid - 1;
			else
				low = mid + 1;//因为low之后的元素不比target小,所以此处是A[low] = target,但仍需向前移动,否则容易陷入死循环。
		}
		if(A[high] == target)
		     v[1] = high;
		else
			v[1] = high - 1;
		return v;
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值