• [Leetcode 89] 34 Search for a Range


    Problem:

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

    Analysis:

    The basic idea is first search for the existence of the target value. If not found, then just return {-1, -1}; If we found one in the given array, then we need to further search for whether there is same element preceeding it and sucseeding it. This procedure is recursive. Until we cannot further find element in the left subpart or right subpart, the result then is correct.

    Code:

     1 class Solution {
     2 public:
     3     vector<int> searchRange(int A[], int n, int target) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<int> res;
     7         int s = 0, e = n-1, l = -1, r = -1;
     8         
     9         while (s <= e) {
    10             int m = (s + e) / 2;
    11             
    12             if (A[m] == target) {
    13                 l = r = m;
    14                 int old_l, old_r;
    15                 while (l != -1) {
    16                     old_l = l;
    17                     l = search(A, s, l-1, target);
    18                 }
    19                     
    20                 while (r != -1) {
    21                     old_r = r;
    22                     r = search(A, r+1, e, target);
    23                 }
    24                 
    25                 l = old_l;
    26                 r = old_r;
    27                 break;
    28             } else  if (A[m] > target)
    29                 e = m-1;
    30             else
    31                 s = m+1;
    32         }
    33         
    34         res.push_back(l);
    35         res.push_back(r);
    36         
    37         return res;
    38     }
    39     
    40 private:
    41     int search(int A[], int s, int e, int t) {
    42         while (s <= e) {
    43             int m = (s+e) / 2;
    44             
    45             if (A[m] == t) {
    46                 return m;
    47             } else if (A[m] > t)
    48                 e = m - 1;
    49             else
    50                 s = m + 1;
    51         }
    52         
    53         return -1;
    54     }
    55 };
    View Code
  • 相关阅读:
    php checkbox 复选框
    wp7 The remote connection to the device has been lost
    php json_decode null
    今入住博客园,希望笑傲职场!
    单例模式之见解设计模式
    简单工厂之见解设计模式
    infopath 序列化 在发布处有导出源文件.存放一地方后有myschema.xsd 文件
    超简单的天气预报webpart
    用户控件传值
    Proxy代理
  • 原文地址:https://www.cnblogs.com/freeneng/p/3218919.html
Copyright © 2020-2023  润新知