LeetCode: Search Insert Position

来源:互联网 发布:淘宝帐号买家卖家分开 编辑:程序博客网 时间:2024/05/16 17:22

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

class Solution {public:    int searchInsert(int A[], int n, int target) {        if(n == 0)return 0;return binarySearch(0, n-1, target, A, n/2);    }int binarySearch(int start, int end, int target, int A[], int preMid){if(start > end){if(A[preMid] < target){return preMid+1;}else{return preMid;}}int mid = (start + end) / 2;if(A[mid] == target)return mid;else if(A[mid] < target){return binarySearch(mid+1, end, target, A, mid);}else{return binarySearch(start, mid-1, target, A, mid);}}};

Round 2:

class Solution {public:    int searchInsert(int A[], int n, int target) {        int l = 0, r = n-1;        while(l <= r)        {            int mid = (l+r)/2;            if(A[mid] == target)                return mid;            else if(A[mid] < target)            {                if(mid == n-1)                    return n;                if(A[mid+1] > target)                    return mid+1;                l = mid+1;            }            else            {                if(mid == 0)                    return 0;                if(A[mid-1] < target)                    return mid;                r = mid-1;            }        }        return 0;    }};


0 0