zoukankan      html  css  js  c++  java
  • 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].

    • 说明:

                  1)已排序数组查找,二分查找

    • 实现:
    1. STL实现
     1 class Solution {
     2 public:
     3     vector<int> searchRange(int A[], int n, int target) {
     4        auto low_bound=lower_bound(A,A+n,target);//第一个大于等于>=target元素的指针位置
     5        auto up_bound=upper_bound(low_bound,A+n,target);//第一个大于>target元素的指针位置
     6        if(*low_bound==target)//target是否存在于A[]
     7        {
     8            return vector<int>{distance(A,low_bound),distance(A,prev(up_bound))};
     9        }
    10        else return vector<int>{-1,-1};
    11         
    12     }
    13 };

         2.  常规实现

     1 class Solution {
     2 public:
     3     vector<int> searchRange(int A[], int n, int target) {
     4         int low=0,high=n-1,middle;
     5         bool isFind=false;
     6         vector<int> vec;
     7         while(low<=high)//二分查找,直至找到,并置标志true
     8         {
     9             middle=(low+high)/2;
    10             if(A[middle]==target) 
    11             {
    12                 isFind=true;
    13                 break;
    14             }
    15             else if(A[middle]<target)
    16                 low=middle+1;
    17             else
    18                 high=middle-1;
    19         }
    20         if(isFind)//如果找到,确定开始、结束与target相等的元素位置
    21         {
    22             low=middle;
    23             high=middle;
    24             while(low>=0&&A[low]==target) low--;//下界要>=0
    25             low++;
    26             while(high<=n-1&&A[high]==target) high++;//上界要<=n-1
    27             high--;
    28             vec.push_back(low);
    29             vec.push_back(high);
    30         }
    31         else//没有目标值
    32         {
    33             vec.push_back(-1);
    34             vec.push_back(-1);
    35         }
    36         return vec;
    37     }
    38 };
  • 相关阅读:
    鲁迅说过搜索引擎
    下载github上文件与release的安装包-解决s3.amazonaws.com问题
    作业九----DFA最小化
    作业八----非确定的自动机NFA确定化为DFA
    作业七----正规式到正规文法与自动机
    作业六----正规文法与正规式
    第五次作业----词法分析程序的设计与实现
    第四次作业
    作业三
    2.文法和语言
  • 原文地址:https://www.cnblogs.com/zhoutaotao/p/3837274.html
Copyright © 2011-2022 走看看