[LeetCode] Search Insert Position

纵然是瞬间 提交于 2020-04-01 05:42:13

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 };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!