zoukankan      html  css  js  c++  java
  • Search Insert Position

    #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);
    }
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    火币Huobi API Websocket
    火币Huobi API
    OKEX API(Websocket)
    OKEX API
    Linux下Miniconda量化环境安装
    Numba:高性能Python编译器
    十进制和十六进制互相转换
    JavaScript 原型和原型链
    Redux 进阶之 react-redux 和 redux-thunk 的应用
    Vue 中 $nextTick() 的应用
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12194996.html
Copyright © 2011-2022 走看看