簡體   English   中英

解決C#中最長的數組子序列程序

[英]Solve the Longest Array Subsequence program in C#

SO中已經問過這個問題:

最長的遞增子序列

但解決方案是使用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)如何優化程序

我至少在這種情況下才發明了一種超快的 ;-)算法(它仍然需要動態索引優化,但是它可以工作):

我的算法使用tolerance/distance來指定數字與其排序索引之間的距離。 根據我繪制的圖像:

在此處輸入圖片說明

結果證明,至少在這里,距離2使我們得到了正確的結果(=最接近其排序位置的數字)。 我必須進行更多調查,但似乎可以完成工作。

(我能想到的)有兩種情況,我們如何找到遞增的順序:

  • 第一種情況-公差為正。 這使我們得到的結果為: 0, 2, 6, 9 , 11, 15
  • 第二種情況-公差為負。 這將給我們: 0, 4, 6, 9 , 13, 15

我在鏈接的問題中看到了另一個這樣的結果: 0, 2, 6, 9 , 13, 15但是我認為如果將其與兩種情況和圖像進行比較是錯誤的並且不一致,因為如果我們采用2我們將13之后。 我們必須像在數組開始時取2一樣取11 比較4, 12, 213, 3, 11

這是代碼:

class Program
{
    static void Main(string[] args)
    {
        //int[] seq = new int[] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
        //int[] seq = new int[] { 0, 8, 4, 2, 12, 10, 6, 14, 1, 9, 5, 7, 3, 11, 15, 13 };
        //int[] seq = new int[] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 16, 7, 15, 11 };
        //int[] seq = new int[] { 3, 1, 2, 5, 4, 8, 6 };
        int[] seq = new int[] { 6, 3, 4, 8, 10, 5, 7, 1, 9, 2 };
        var result = longestSeq3(seq);
    }

    private static List<int> longestSeq3(int[] seq)
    {
        int maxDist = 2;
        List<int> result = new List<int>();

        for (int i = 0; i < seq.Length; i++)
        {
            int current = seq[i];
            int dist = Math.Abs(i - current);
            if (dist >= 0 && dist <= maxDist)
            {
                if (result.Count > 0 && current <= result.Last())
                {
                    continue;
                }
                result.Add(current);
            }
        }

        return result;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM