• [leetcode] 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].
     
    分析:二分查找
     1 class Solution
     2 {
     3 public:
     4   void Searching(vector<int> &ret, int A[], int s, int e, int target)
     5   {
     6     if(s > e)
     7     {
     8       ret.push_back(-1);
     9       ret.push_back(-1);
    10       return;
    11     }
    12 
    13     int mid = (s+e)/2;
    14     if(A[mid] < target)
    15       Searching(ret, A, mid+1, e, target);
    16     else if(A[mid] > target)
    17       Searching(ret, A, s, mid-1, target);
    18     else
    19     {
    20       int i = mid - 1;
    21       while(i >= s && A[i] == A[mid]) i--;
    22       ret.push_back(i + 1);
    23 
    24       i = mid + 1;
    25       while(i <= e && A[i] == A[mid]) i++;
    26       ret.push_back(i - 1);
    27     }
    28   }
    29   vector<int> searchRange(int A[], int n, int target)
    30   {
    31     vector<int> ret;
    32     if(target < A[0] || target > A[n-1])
    33     {
    34       ret.push_back(-1);
    35       ret.push_back(-1);
    36     }
    37     else
    38       Searching(ret, A, 0, n-1, target);
    39 
    40     return ret;
    41   }
    42 };
  • 相关阅读:
    直线型一阶倒立摆5---硬件平台搭建
    PE view---重要参数--C语言实现
    A1132. Cut Integer
    A1131. Subway Map (30)
    A1130. Infix Expression
    A1129. Recommendation System
    A1128. N Queens Puzzle
    A1127. ZigZagging on a Tree
    A1126. Eulerian Path
    A1125. Chain the Ropes
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4344537.html
Copyright © 2020-2023  润新知