zoukankan      html  css  js  c++  java
  • leetcode Search for a Range

    代码:

     1 #include<iostream>
     2 #include<vector>
     3 
     4 using namespace std;
     5 
     6 int searchSmallest(int A[], int n, int target){
     7     int l = 0;
     8     int r = n - 1;
     9     while (l <= r){
    10         int mid = (l + r) / 2;
    11         if (target <= A[mid]){
    12             r = mid-1;
    13         }
    14         else{
    15             l = mid+1;
    16         }
    17     }
    18     if (A[r + 1] == target)
    19         return r + 1;
    20     else
    21         return -1;
    22 }
    23 
    24 int searchLargest(int A[], int n, int target){
    25     int l = 0;
    26     int r = n - 1;
    27     while (l <= r){
    28         int mid = (l+ r) / 2;
    29         if (target >= A[mid]){
    30             l = mid+1;
    31         }
    32         else{
    33             r = mid - 1;
    34         }
    35     }
    36     if (A[l-1] == target)
    37         return l - 1;
    38     else
    39         return -1;
    40 }
    41 
    42 vector<int> searchRange(int A[], int n, int target) {
    43     vector<int> result;
    44     int a = searchSmallest(A, n, target);
    45     int b = searchLargest(A, n, target);
    46     result.push_back(a);
    47     result.push_back(b);
    48     return result;
    49 }
    50 
    51 int main(){
    52     int a[] = {1};
    53     cout << searchSmallest(a, 1, 1) << endl;
    54     cout << searchLargest(a, 1, 1) << endl;
    55     vector<int> result = searchRange(a, 1, 1);
    56     for (int i = 0; i < result.size(); i++){
    57         cout << result[i] << endl;
    58     }
    59 }
  • 相关阅读:
    获取客户及登录IP(Java)
    js初步
    数组方法
    BOM ;浏览器对象模型
    js事件
    EventListener()
    JS面向对象
    正则表达式
    -CSS盒模型和float
    EventListener()
  • 原文地址:https://www.cnblogs.com/chaiwentao/p/4448846.html
Copyright © 2011-2022 走看看