zoukankan      html  css  js  c++  java
  • 数据结构时间复杂度

    问题引出:

    编程找出指定数列的所有子列和的最大值;

    假定数列:

    int arry[16] = {5, -6, 4, -5, 3, 1, 2, -4, 8, -9, 3, 1, -7, 6, 4, -1};
     
    算法一:
    #include <iostream>
    using namespace std;
    int main()
    {
        const int N = 16;
        int arry[N] = {5, -6, 4, -5, 3, 1, 2, -4, 8, -9, 3, 1, -7, 6, 4, -1};
        int maxsum = 0;
        
        for (int k = 0; k < N; k++)
        {
            for (int j = k; j < N; j++)
            {
                int tempsum = 0;
                for (int i = k; i <= j; i++)
                {
                    tempsum += arry[i];  
                }
                maxsum = tempsum > maxsum ? tempsum : maxsum;
            }
        }
        cout << maxsum << endl;
        return 0;
    }

    例用三个循环:其时间复杂度T(N) = O(N3);

    算法二:

    #include <iostream>
    using namespace std;
    int main()
    {
        const int N = 16;
        int arry[N] = {5, -6, 4, -5, 3, 1, 2, -4, 8, -9, 3, 1, -7, 6, 4, -1};
        int maxsum = 0;
        
        for (int k = 0; k < N; k++)
        {
            int tempsum = 0;
            for (int j = k; j < N; j++)
            {
                tempsum += arry[j];    
                maxsum = tempsum > maxsum ? tempsum : maxsum;
            }
        }
        cout << maxsum << endl;
        return 0;
    }

    例用两个循环:其时间复杂度T(N) = O(N2);

    算法三:

    #include <iostream>
    using namespace std;
    int main()
    {
        const int N = 15;
        int arry[N] = {5, -6, 4, 5, 3, 1, 2, -4, 8, -9, 3, 1, -7, 6, -4};
        int maxsum = 0;
        int tempsum = 0;
        for (int k = 0; k < N; k++)
        {
            tempsum += arry[k];
            if (tempsum < 0)
            {
                tempsum = 0;
            }
            else
            {
                maxsum = maxsum > tempsum ? maxsum : tempsum;
            }
            
        }
        cout << maxsum << endl;
        return 0;
    }

    例用一个循环:其时间复杂度T(N) = O(N);

  • 相关阅读:
    python中取列表的后半部分元素
    python中列表分片
    python中统计列表中元素出现的次数
    python中range()函数用法
    pyhton中实现列表元素顺序颠倒
    python中列表元素求交集和并集
    python中编写抽奖小游戏
    python中删除列表元素
    python中列表的去重复和取重复
    欲为Java技术大牛所需的25个学习要点
  • 原文地址:https://www.cnblogs.com/flowingwind/p/8443585.html
Copyright © 2011-2022 走看看