最大连续子序列,返回子序列和长度

时间:2020-03-20 13:45:37

标签: java algorithm subsequence

我有一个返回子序列长度的函数,但是我也需要返回子序列本身,但是我很难使它起作用。

我尝试了以下代码,但是只有当第一个子序列最长时,子序列才能正确返回。

如果我使用以下数组,则长度10是正确的,但它返回的错误子序列[1、2、3、4、10、11、12、13、14、15]

$id_list_arr = explode(" ",$id_list);

$args = array(
'posts_per_page'    => -1,
'post_type' => array('features', 'reviews'),
'orderby' => 'post__in', 
'post__in' =>  $id_list_arr
);

1 个答案:

答案 0 :(得分:1)

这似乎是确定序列的一种round回的方式。

我相信您的缺点之一在这里:

// if current element is the starting 
// element of a sequence 
if (!S.contains(arr[i]-1)) 
{ 

这肯定是有缺陷的。 假设您有输入序列{1,3,5,2,4,6}。该列表中没有2个或更多的序列。但是,从2到6的输入将通过您对S.contains(arr[i]-1)的测试,因为S HashSet包含1,2,3,4,5,6。

这是我认为找到最长序列的一种更简单的方法:

int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
int currentLength = 1;

for(int i=1;i<arr.length;i++)
{
     if (arr[i] == arr[i-1] + 1)
     {
         // this element is in sequence.
         currentLength++;
         if (currentLength > longestLength)
         {
             longestLength = currentLength;
             longestStart = currentStart;
         }
     }
     else
     {
          // This element is not in sequence.
         currentStart = i;
         currentLength = 1;
     }
}
System.out.printlng(longestStart + ", " + longestLength);
相关问题