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     vector<int> searchRange(int A[], int n, int target) {
     4         vector<int> ret(2, -1);
     5         int start = 0, end = n - 1;
     6         int mid;
     7         bool found = false;
     8         while (start <= end && !found) {
     9             mid = (start + end) / 2;
    10             if (A[mid] == target) {
    11                 found = true;
    12             } else if (A[mid] < target) {
    13                 start = mid + 1;
    14             } else {
    15                 end = mid - 1;
    16             }
    17         }
    18         if (found) {
    19             start = mid;
    20             while (start - 1 >= 0 && A[start - 1] == target) {
    21                 --start;
    22             }
    23             end = mid;
    24             while (end + 1 < n && A[end + 1] == target) {
    25                 ++end;
    26             }
    27             ret[0] = start;
    28             ret[1] = end;
    29         }
    30         return ret;
    31     }
    32 };
    View Code

    二分查找。

  • 相关阅读:
    IE8、IE9解决浏览器跨域。
    英语写作-Introduction
    qt添加图标
    Qt 编译错误 :cannot find file .pro
    python
    数据集
    基金
    visio2010求交操作
    书籍网站
    ROS安装xtion
  • 原文地址:https://www.cnblogs.com/dengeven/p/3740923.html
Copyright © 2011-2022 走看看