如何利用C++、Java、Python找出由连续的整数组成的最长的子序列

112 阅读1分钟

问题

给定一个整数数组,找出连续整数的最长子序列。

输入样本

[1, 2, 3, 4, 55]

输出示例

4

解释

The subsequence is [1, 2, 3, 4]

方法

我们可以插入一个集合中的所有元素。然后我们寻找一个子序列的起始元素。为了检查这一点,假设当前元素是 arr[i],那么如果 arr[i] -1 在这个集合中没有找到,那么这就是子序列的起始元素。然后我们可以迭代到 ,并更新答案。这种方法需要O(N)时间和O(N)空间。arr[i]+1

C++编程

#include <bits/stdc++.h>
using namespace std;

int solve(int arr[], int n)
{
    unordered_set<int> s;
    int ans = 0;

    for (int i = 0; i < n; i++)
        s.insert(arr[i]);

    for (int i = 0; i < n; i++)
    {

        if (s.find(arr[i] - 1) == s.end())
        {

            int j = arr[i];
            while (s.find(j) != s.end())
                j++;

            ans = max(ans, j - arr[i]);
        }
    }
    return ans;
}

int main()
{
    int arr[] = { 1, 2, 3, 4, 55 };
    int n = sizeof arr / sizeof arr[0];
    cout << "Length of subsequence is " << solve(arr, n);
    return 0;
}

输出

Length of subsequence is 4

Python编程

def solve(arr, n):
    s = set()
    ans = 0
    for itr in arr:
        s.add(itr)
    for i in range(n):
        if (arr[i]-1) not in s:
            j = arr[i]
            while(j in s):
                j += 1
            ans = max(ans, j-arr[i])
    return ans



arr = [1, 2, 3, 4, 55]
n = len(arr)
print("Length of subsequence is ", end=" ")
print(solve(arr, n))

输出

Length of subsequence is 

C#编程

using System;
using System.Collections.Generic;

public class Solutions {

    public static int solve(int[] arr, int n)
    {
        HashSet<int> s = new HashSet<int>();
        int ans = 0;

        for (int i = 0; i < n; ++i) {
            s.Add(arr[i]);
        }


        for (int i = 0; i < n; ++i)
        {

            if (!s.Contains(arr[i] - 1))
            {

                int j = arr[i];
                while (s.Contains(j))
                {
                    j++;
                }

                if (ans < j - arr[i])
                {
                    ans = j - arr[i];
                }
            }
        }
        return ans;
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 55 };
        int n = arr.Length;
        Console.WriteLine(
            "Length of subsequence is "
            + solve(arr, n));
    }
}

输出

Length of subsequence is 4