zoukankan      html  css  js  c++  java
  • 计蒜客 寻找插入位置 (二分查找)

    给定一个已经升序排好序的数组,以及一个数 target,如果 target 在数组中,返回它在数组中的位置。

    否则,返回 target插入数组后它应该在的位置。

    假设数组中没有重复的数。以下是简单的示例:

    [1,3,5,6], 5 → 2

    [1,3,5,6], 2 → 1

    [1,3,5,6], 7 → 4

    [1,3,5,6], 0 → 0

    输入格式

    第一行输入一个整数 n

    第二行输入 n 个整数,表示数组A[n]

    第三行输入 target

    输出格式

    输出一行,为要求返回的结果。

    样例输入

    3
    1 3 5
    2

    样例输出

    1
     1 #include <iostream>
     2 using namespace std;
     3 
     4 int binarySearch(int *a, int left, int right, int target){
     5     int middle;
     6     //target在数组中
     7     while(left <= right){
     8         middle = (right - left) / 2 + left;
     9         if(target == a[middle])
    10             return middle;
    11         else if(target < a[middle])
    12             right = middle - 1;
    13         else 
    14             left = middle + 1;
    15     }
    16     //target不在数组中,而且此时left == right
    17     if(target < a[middle])
    18         return middle;
    19     else
    20         return middle + 1;
    21 }
    22 int main(){
    23     int n, target;
    24     cin >> n;
    25     int *a = new int[n];
    26     for(int i = 0; i < n; i++){
    27         cin >> a[i];
    28     }
    29     cin >> target;
    30     int ans = binarySearch(a, 0, n - 1, target);
    31     cout << ans << endl;
    32     return 0;
    33 }
    
    
    
    
    
  • 相关阅读:
    注意事项 软件连接的数据库是设置输出的数据库,弄错会造成数据库不一致
    归并排序
    快速排序
    冒泡排序
    插入排序
    上次遗留下来的XMLUtil的问题
    关于子网掩码
    java.lang.InstantiationException
    java.lang.ExceptionInInitializerError
    关于HashMap中的负载因子
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5671972.html
Copyright © 2011-2022 走看看