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

LeetCode链接:https://oj.leetcode.com/problems/search-for-a-range/

算法解析:

   本算法要求:给定一个有序数组和目标值,能够检索出目标值在数组中的起始索引,如果目标不在数组中,则返回【-1,-1】,而且要求了时间性能。通过分析,很容易知道,该算法是Search Insert Position算法(详细可以参考上一篇blog)的扩展。还是从最简单的顺序查找算法入手,当然你也可以像上个算法一样,从前到后遍历找到开始索引,然后再从后向前遍历找到结束索引。但是,笔者经过思考后没有采取这种思路,而是对上一个算法进行了改进,设计两个变量i(记录开始索引)、j(记录结束索引),然后同时从数组两边进行遍历,这样最多遍历一遍数组即可找到起始索引。解决方案如下:

class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> result;
        result.push_back(-1);
        result.push_back(-1);
        if ((target < A[0]) || (target > A[n - 1]))     //a.处理目标不在数组范围的情况
        {
            return result;
        }
        if ((n == 2) && (A[0] != target) && (A[1] != target))   //b.处理数组长度为2,目标在数组范围,但是在数组中不存在的情况
        {
            return result;
        }
        int i = 0;
        int j = n - 1;
        while  (target > A[i] || target < A[j])
        {
            if (i == j)     //结束条件
            {
                break;
            }
            if (target > A[i])
            {
                i++;    
            }
            if (target < A[j])
            {
                j--;
            }
        }
        if ((i == j) && (A[i] != target))   //c.处理数组长度不等于2,目标在数组范围,但是在数组中不存在的情况
        {
            return result;
        }
        result[0] = i;
        result[1] = j;
        return result;
    }
};
   正如代码中的注释,你需要对一些特殊情况进行处理。注释a的情况,很简单,就是为了处理目标不在给定数组范围的情况。如果,你不处理b的情况,可能会给出类似与以下的错误:
    为什么会出现这种错误呢,因为如果没有注释b处的代码,经过while循环后:i=1,j=0,所以就出现了上图的结果。注释c处的解释已经很清楚,这里不再赘述了。
性能分析:    

   按照上面的解决方案,AC可以通过,仅用了56ms就分析了81个测试案例,结果如下图所示:

 其他实现思路:

待续!!!

  Python解决方案:
待续!!!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值