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 class Solution {
     2 public:
     3     int findPos(int a[], int beg, int end, int key, bool findLeft)
     4     {
     5         if (beg > end)
     6             return -1;
     7             
     8         int mid = (beg + end) / 2;
     9         
    10         if (a[mid] == key)
    11         {
    12             int pos = findLeft ? findPos(a, beg, mid - 1, key, findLeft) : findPos(a, mid + 1, end, key, findLeft);
    13             return pos == -1 ? mid : pos;
    14         }
    15         else if (a[mid] < key)
    16             return findPos(a, mid + 1, end, key, findLeft);
    17         else
    18             return findPos(a, beg, mid - 1, key, findLeft);       
    19     }
    20     
    21     vector<int> searchRange(int A[], int n, int target) {
    22         // Start typing your C/C++ solution below
    23         // DO NOT write int main() function
    24         int leftPos = findPos(A, 0, n - 1, target, true);
    25         int rightPos = findPos(A, 0, n - 1, target, false);
    26         
    27         vector<int> ret;
    28         
    29         ret.push_back(leftPos);
    30         ret.push_back(rightPos);
    31         return ret;
    32     }
    33 };
  • 相关阅读:
    ascii、unicode、utf-8、gbk 区别?
    python递归的最大层数?
    线程
    为何基于tcp协议的通信比基于udp协议的通信更可靠?
    什么是局域网和广域网?
    通过代码实现如下转换 ?
    TCP和UDP的区别?
    什么是ARP协议?
    PEP8 常用规范
    b、B、KB、MB、GB 的关系?
  • 原文地址:https://www.cnblogs.com/chkkch/p/2770148.html
Copyright © 2011-2022 走看看