zoukankan      html  css  js  c++  java
  • [LeetCode] Search for a Range

    The idea is to search for the left and right boundaries of target via two binary searches. Well, some tricks may be needed. Take a look at this link :-)

    The code is rewritten as follows.

     1 class Solution {
     2 public:
     3     vector<int> searchRange(vector<int>& nums, int target) {
     4         int l = left(nums, target);
     5         if (l == -1) return {-1, -1};
     6         return {l, right(nums, target)};
     7     }
     8 private:
     9     int left(vector<int>& nums, int target) {
    10         int n = nums.size(), l = 0, r = n - 1;
    11         while (l < r) {
    12             int m = l + ((r - l) >> 1);
    13             if (nums[m] < target) l = m + 1;
    14             else r = m;
    15         }
    16         return nums[l] == target ? l : -1;
    17     }
    18     int right(vector<int>& nums, int target) {
    19         int n = nums.size(), l = 0, r = n - 1;
    20         while (l < r) {
    21             int m = l + ((r - l + 1) >> 1); 
    22             if (nums[m] > target) r = m - 1;
    23             else l = m;
    24         }
    25         return r;
    26     }
    27 }; 
  • 相关阅读:
    FastDFS的简单使用
    KindEditor的简单使用
    rpc
    SDS——动态字符串
    图的深度优先遍历和广度优先遍历
    innodb和myisam原理
    cap理论
    冒泡排序
    桥接模式
    适配器模式
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4732657.html
Copyright © 2011-2022 走看看