zoukankan      html  css  js  c++  java
  • 【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 public:
     3     vector<int> searchRange(int A[], int n, int target) {
     4        
     5  
     6         vector<int>res(2);          
     7  
     8         res[0]=bs(A,n,target-1)+1;
     9         res[1]=bs(A,n,target);        
    10   
    11         if(res[1]==-1||A[res[1]]!=target)
    12         {
    13             res[0]=-1;
    14             res[1]=-1;
    15         }          
    16         return res;
    17     }
    18    
    19     //通过这个二分查找,如果有多个target的话可以找到最靠右边的元素
    20     //同时也得注意,如果没有target则找到的是比target小的最大的最靠右元素
    21      int bs(int A[],int n,int target)
    22     {
    23         int left=0;
    24         int right=n-1;
    25         int mid=(left+right)/2;
    26         int ret=-1;
    27        
    28         while(left<=right)
    29         {
    30             if(A[mid]>target)
    31             {
    32                 right=mid-1;
    33             }
    34             else
    35             {
    36                 //只要是当前元素小于等于target,left就会右移,因此找到最靠右的元素
    37                 ret=mid;
    38                 left=mid+1;
    39             }
    40             mid=(left+right)/2;
    41         }          
    42         return ret;
    43     }
    44    
    45 };
  • 相关阅读:
    uni-app-数据缓存
    uni-app-网络请求
    uni-app-上拉加载
    uni-app-下拉刷新
    uni-app-生命周期
    uni-app字体图标
    uni-app-样式
    [Python] ValueError: Unknown resampling filter
    [Python]列表复制以及切片[:][::]解析
    LeetCode 29. 两数相除
  • 原文地址:https://www.cnblogs.com/reachteam/p/4245958.html
Copyright © 2011-2022 走看看