用C#解决最长数组子序列程序

时间:2014-12-29 07:19:29

标签: c#

问题已在SO中提出:

Longest increasing subsequence

但解决方案是Python。

这是我的C#版本

private static int longestSeq(int[] input1)
            {                
                int counter = 0;
                int i = 0;
                int x = 0;
                bool flag = true;

                if (input1.Length == 0) return 0;
                if (input1.Length == 1) return 1;

                while (i != input1.Length-1)
                {
                     if (flag)x= input1[i];
                    int y = input1[i + 1];
                    if (x < y) { counter++; flag = true; }
                    else { if (flag) { x = input1[i]; flag = !flag; } }
                    i++;
                }

                return counter+1;
            }

但它不适用于

int[] input1 = new int[] { 0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15 };

预期输出为6但我得到5。

2个问题

a)我错过了什么?

b)如何优化我的程序

1 个答案:

答案 0 :(得分:1)

我现在至少在这种情况下发明了一个超高速 ;-)算法(它仍然需要动态索引优化,但它有效):

我的算法使用tolerance/distance,指定一个数字与排序索引的距离。根据我画的图像:

enter image description here

事实证明,至少在这里,2的距离给出了我们的结果(=最接近其排序位置的数字)。我必须更多地调查它,但它似乎做了工作。

可以有两种情况(我能想到)我们如何找到增加的序列:

  • 第一种情况 - 容忍度为正。这为我们提供了一个结果:0, 2, 6, 9 , 11, 15
  • 第二种情况 - 容忍度为负。这会给我们:0, 4, 6, 9 , 13, 15

我在链接的问题中看到了另一个结果:0, 2, 6, 9 , 13, 15但我认为如果你将它与两个案例和图像进行比较是错误和不一致的,因为如果我们采用{{1}我们以后不能接受2。我们必须采用13,就像我们在数组的开头采用11一样。比较24, 12, 2

以下是代码:

13, 3, 11