[leetcode_35]Search Insert Position

简单题,二分。
找到了返回下标,找不到返回应该放的位置的下标。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
    int ans;
    int searchInsert(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        ans = 0;
        bsearch(0,n-1,A,target);
        return  ans;
    }
    void bsearch(int left,int right,int A[],int target)
    {
        if(left > right)
        {
            ans = left;
            return ;
        }
        int mid = (left + right) / 2;
        if(A[mid] == target)
        {
            ans = mid;
            return ;
        }
        else
            if(A[mid] > target)
            {
                bsearch(left,mid-1,A,target);
            }
            else
            {
                bsearch(mid+1,right,A,target);
            }
    }
};
Licensed under CC BY-NC-SA 4.0