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 };
  • 相关阅读:
    4.18下午
    4.18上午
    2017.5.10-afternoon
    2017.5.9-afternoon
    2017.5.10-morning
    2017.5.9-morning
    2017.5.8-afternoon
    2017.5.8-morning
    2017.5.5-afternoon
    2017.5.5-morning
  • 原文地址:https://www.cnblogs.com/chkkch/p/2775647.html
Copyright © 2011-2022 走看看