zoukankan      html  css  js  c++  java
  • [LeetCode] Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

    You may assume no duplicates in the array.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    二分搜索的修改版

     1 class Solution {
     2 public:
     3     int bsearch(int a[], int left, int right, int key)
     4     {
     5         if (left > right)
     6             return left;
     7             
     8         int mid = left + (right - left) / 2;
     9         
    10         if (a[mid] == key)
    11             return mid;
    12         else if (a[mid] < key)
    13             return bsearch(a, mid + 1, right, key);
    14         else
    15             return bsearch(a, left, mid - 1, key);
    16     }
    17     
    18     int searchInsert(int A[], int n, int target) {
    19         // Start typing your C/C++ solution below
    20         // DO NOT write int main() function
    21         return bsearch(A, 0, n - 1, target);
    22     }
    23 };
  • 相关阅读:
    vue 響應接口
    vue ajax
    vue混入
    vue動畫和過渡
    vue路由
    vue自定義指令
    python项目_使用极验验证码
    python项目_使用异步功能,celery
    python项目_集成短信发送功能
    python项目_redis使用
  • 原文地址:https://www.cnblogs.com/chkkch/p/2775647.html
Copyright © 2011-2022 走看看