【LeetCode】34_Search for a Range

题目

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














解析

题目很简单,就是普通的查找,主要是要求时间复杂度O(log n),所以我想到的方法就是二分查找法。

与一般二分查找不同的是,这个序列有可能出现重复的的数字,我的解决方法是二分法,然后如果中位数正好等于target了,就往前和往后搜索即可。

最后再针对几种可能出现的情况分类讨论一下就好了。

代码如下

class Solution {
public:
	void serachMy(vector<int>& nums, int start, int end, int target,vector<int>& ss)
	{
		if (start == end)
		{
			if (nums[start] == target)
			{
				ss.push_back(start);
			}
			return;
		}
		int mid = (end - start)/2+start;
		
		if (nums[mid] < target)
		{
			serachMy(nums, mid+1>nums.size()?mid:mid+1, end, target,ss);
		}
		else if(nums[mid] > target)
		{
			serachMy(nums, start, mid-1<0?mid:mid-1, target,ss);
		}
		else
		{
			int flagEnd = mid;
			while (flagEnd<nums.size() && nums[flagEnd] == target)
			{
				flagEnd++;
			}
			int flagStart = mid;
			while (flagStart>=0 && nums[flagStart] == target)
			{
					flagStart--;
			}
			ss.push_back(flagStart+1);
			ss.push_back(flagEnd-1);
			return;
		}
	}
    vector<int> searchRange(vector<int>& nums, int target) {
       <span style="white-space:pre">	</span>        vector<int> ss;
		vector<int> ret;
		serachMy(nums, 0, nums.size()-1,target,ss);

		if (ss.empty())
		{
			ret.push_back(-1);
			ret.push_back(-1);
		}
		else if (ss.size()==1)
		{
			ret.push_back(ss[0]);
			ret.push_back(ss[0]);
		}
		else
		{
			ret.push_back(ss[0]);
			ret.push_back(ss.back());
		}
		return ret;
    }
};

方法比较中规中矩,主要是注意一下边界条件。

再看看大神的代码。

class Solution {
public:
	vector<int> searchRange(int A[], int n, int target) {
    const int l = distance(A, lower_bound(A, A + n, target));
    const int u = distance(A, prev(upper_bound(A, A + n, target)));
    if (A[l] != target) // not found
        return vector<int> { -1, -1 };
    else
        return vector<int> { l, u };
    }
};
什么也不想说了,用了这么多STL的函数。来总结一下知识点。

1.back()函数

可以取vector的最后一个元素。如 nums.back()

2.lower_bound()

函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~

3.upper_bound()

函数upper_bound()返回的在前闭后开区间查找的关键字的上界,如一个数组number序列1,2,2,4.upper_bound(2)后,返回的位置是3(下标)也就是4所在的位置,同样,如果插入元素大于数组中全部元素,返回的是last。(注意:此时数组下标越界!!)

返回查找元素的最后一个可安插位置,也就是“元素值>查找值”的第一个元素的位置

4.distance

c++中,distance为一函数模版,返回两个迭代器间的距离







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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值