• 对数复杂度算法


      二分搜索(binary search):给定一个整数X和整数A1,A1,...,AN-1,后者已经预先排序并在内存中,求下标 i 使得 Ai = X,如果X不在数据中,则返回-1。

     1 #include <iostream>
     2 #include <vector>
     3 using namespace std;
     4 
     5 const int NOT_FOUND = -1;
     6 template <typename Comparable>
     7 int binarySearch(const vector<Comparable> &a, const Comparable &x) {
     8     int low = 0, high = a.size() - 1;
     9     while(low <= high) {
    10         int mid = (low + high) / 2;
    11         if(a[mid] < x) {
    12             low = mid + 1;
    13         } else if(a[mid] > x) {
    14             high = mid - 1;
    15         } else {
    16             return mid;
    17         }
    18     }
    19     return NOT_FOUND;
    20 }    //时间复杂度为O(logN)
    21 
    22 int main() {
    23     vector<int> a;
    24     for(int i = 0; i < 20; ++i) {
    25         a.push_back(i * 2);
    26     }
    27     int mid;
    28     mid = binarySearch(a, 16);
    29     cout << mid << endl;
    30     return 0;
    31 }

    欧几里得算法

     1 #include <iostream>
     2 #include <vector>
     3 using namespace std;
     4 
     5 long gcd(long m, long n) {
     6     //欧几里得算法
     7     //m大于等于n
     8     while(n != 0) {
     9         long rem = m % n;
    10         m = n;
    11         n = rem;
    12     }
    13     return m;
    14 }    //时间复杂度为O(logN)
    15 
    16 int main() {
    17     cout << gcd(50, 15) << endl;
    18     cout << gcd(1989, 1590) << endl;
    19     return 0;
    20 }

    幂运算:如果N是偶数,XN = XN/2 * XN/2,如果N是奇数,则XN = X(N-1)/2 * X(N-1)/2 * X。

     1 #include <iostream>
     2 #include <vector>
     3 using namespace std;
     4 
     5 long pow(long x, int n) {
     6     if(n == 0)
     7         return 1;
     8     if(n == 1) 
     9         return x;
    10     if(n%2 == 0)
    11         return pow(x * x, n/2);
    12     else 
    13         return pow(x * x, n/2) * x;
    14 }
    15 
    16 int main() {
    17     cout << pow(2, 10) << endl;
    18     cout << pow(2, 7) << endl;
    19     return 0;
    20 }

    第11行若替换为 return pow(pow(x * x, 2), n/2); 或 return pow(pow(x, n/2), 2); ,当n是2时,程序会产生一个无限循环。

    当第11行替换为 return pow(x, n/2) * pow(x, n/2); 时,会影响程序的效率。

  • 相关阅读:
    Windows设置多用户同时远程登录
    Scala配置环境变量windows
    Java学习|强引用,软引用,弱引用,幻想引用有什么区别?
    Java学习|Exception和Error有什么区别?
    关于异常处理的几点建议
    win Server 2008 笔记
    .Net 初步学习笔记之三---变量
    认识与入门 MarkDown 标记语言
    C# winform基础 1、Timer不起作用 2、 设置图片透明
    IIS启动失败,启动Windows Process Activation Service时,出现错误13:数据无效 ;HTTP 错误 401.2
  • 原文地址:https://www.cnblogs.com/wjq-Law/p/4901592.html
Copyright © 2020-2023  润新知