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);
    }
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    php5调用web service
    经典SQL语句大全
    15个初学者必看的基础SQL查询语句
    MySQL数据库INSERT、UPDATE、DELETE以及REPLACE语句的用法详解
    mysql update操作
    Oracle CASE WHEN 用法介绍
    日期时间格式正则表达式
    JS的事件监听机制
    JS 事件介绍
    c#格式化数字
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12194996.html
Copyright © 2011-2022 走看看