寻找最长等差数列

(时间复杂度有点高,但是不知道如何优化了,如何更好DP)

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        //从一个已经排好序的数组中找出最长的等差数列,时间复杂度为 O(NUM*N^2)
        //还可以进行优化:1.Array.indexof...函数用二分法,时间复杂度将为O(NUM*N*lgN)
        //2.如果NUM过大,那么可以用穷举法列举出N个数可能的GAP,最多有N^2个,故最终时间复杂度为Min{  O(NUM*N*lgN),  O(N^3*lgN) }
        static void Main(string[] args)
        {
            int []arr=new int[]{-1,2,3,5,7,8,10};

            int Max_Gap = arr[arr.Length - 1] - arr[0];
            int MyGap = 0, MyLast = 0,maxLen=0;
            List<List<int>> result = new List<List<int>>();
            
            for (int i = 0; i <= Max_Gap; i++)
            {
                result.Add(new List<int>(new int[arr.Length]));
                for (int j = 0; j < arr.Length; j++)
                {
                    if (j > 0)
                    {
                        int target = arr[j] - i;
                        int t;
                        t = Array.IndexOf<int>(arr,target);
                        if (t!=-1)
                        {
                            result[i][j] = 1 + result[i][t];
                            if (result[i][j] > maxLen)
                            {
                                maxLen=result[i][j];
                                MyGap = i;
                                MyLast = arr[j];
                            }
                        }
                        else
                            result[i][j] = 0;
                    }
                    else
                        result[i][j] = 0;

                }
            }

            for (int t = maxLen; t>=0; t--)
            {
                Console.Write(" " + (MyLast - t * MyGap));
            }
            Console.WriteLine();

        }
    }
}


 另一算法在某些情况下明显更好(在SUM小的情况下,还是利用上述算法快),转自http://blog.csdn.net/qunqin/article/details/7533097

此算法严格为O(N^3)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值