学会思考
刻意练习
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>

/*
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
*/

using namespace std;
class Solution{
public:
    int searchInsert(int A[], int n, int target){
        int begin = 0;
        int end = n - 1;
        int middle = end / 2;
        while (begin <= end) {
            middle = (begin + end) / 2;
            if(A[middle] == target)
                return middle;
            else if(A[middle] < target)
            {
                begin = middle + 1;
            }
            else
                end = middle - 1;
        }
        return begin;//此时begin > end
    }
};

//method 2:
int binary_search(int A[], int n, int key){
    int low = 0;
    int high = n - 1;
    while (low <= high) {
        int mid = low + (high - low)/2;
        if(A[mid] == key){
            return mid;
        }
        if(key > A[mid])
            low = mid + 1;
        else
            high = mid - 1;
    }
    return low;
}

int searchInsert(int A[], int n, int target){
    if(n == 0) return n;
    return binary_search(A,n,target);
}
posted on 2020-01-15 09:15  Worty  阅读(118)  评论(0编辑  收藏  举报