zoukankan      html  css  js  c++  java
  • 用现成函数进行二分查找

    2017-07-17 12:00:12

    writer:pprp

    题目:找到你想要的数的

    代码如下:

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
          //test
          int n  ;
          int a[10000];
          cin >> n ;
    
          for(int i = 0 ; i < n ; i ++)
          {
                cin >> a[i];
          }
    
          sort(a,a+n);
    
          for(int i = 0 ; i < n ; i++)
          {
                cout << a[i] << endl;
          }
          int x;
    
          unique(a,a+n);
    
          cin >> x;
          cout << lower_bound(a,a+n,x)-a +1<< endl;
    
        return 0;
    }

    lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个不小于value 的值。该函数为C++ STL内的函数。

    所以如果需要取得某元素下标,需要先用sort函数进行排序,然后得到所需元素下标

    常用的用法:

    查找某个元素可以这样查找

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        int n;
        int a[] = {0,2,32,45,344,76756,2345,-123,4323,12321,323,434};
    
        sort(a, a+12);
    
        for(int i = 0 ;  i < 12 ; i++)
        {
            cout << a[i] <<" ";
        }
        cout << endl;
        while(cin >> n)
        {
            cout << " lower_index " << lower_bound(a,a+12,n) - a << endl;
            cout << " upper_bound " << upper_bound(a,a+12,n) - a << endl;
            cout << " cha "  << upper_bound(a,a+12,n) - lower_bound(a,a+12,n) << endl;
        }
        return 0;
    }

    如果找到这个元素那么cha为1否则为0

  • 相关阅读:
    时间戳 时间 相互转换
    CS Academy Remove Update
    一周水题集锦 2017 9.4
    计蒜客 16877 卡牌游戏
    计蒜客 16876 韩梅梅的抽象画
    九度OJ 题目1534:数组中第K小的数字
    CS Academy Switch the Lights
    CF AIM Tech Round 4 C. Sorting by Subsequences
    CF Round 430 C. Ilya And The Tree
    CS Academy Round 44 Check DFS
  • 原文地址:https://www.cnblogs.com/pprp/p/7193726.html
Copyright © 2011-2022 走看看