找到然后删除数组中最长的0序列

时间:2015-06-26 10:35:35

标签: c

我的数组只有0 n 1。 ARR [] = {} 00111000011 我需要找到并删除最长的0序列并计算数组中剩余的元素。

int longestsequence(int[] arr, int size)
{
    int longest = 0;
    int length = 1;
    for (int i = 1; i < size; i++)
        if (arr[i] == arr[i - 1])
        {
            length++;
        }
        else
        {
            length = 1;
        }
    if (length > longest)
    {
        longest = length;
    }
    return longest;

    int count = 0;
    for (int i = 1; i < size; i++)
    {
        if (arr[i] == 0)
            count++;
    }
    if (count > longest)
        longest = count;
}

1 个答案:

答案 0 :(得分:0)

如果我已正确理解了分配,那么该功能可以按照以下方式显示,如下图所示。至少它可以作为你自己的功能的基础

#include <stdio.h>
#include <string.h>

size_t longestsequence( int *a, size_t n )
{
    int *longest_start = a, *longest_end = a;
    int *start;
    int found = 0;

    int *current = a;
    for ( ; current != a + n; ++current )
    {
        if ( *current == 0 && !found ) 
        {
            found = 1;
            start = current;
        }            
        else if ( *current == 1 && found )
        {
            found = 0;
            if ( longest_end - longest_start < current - start )
            {
                longest_start = start;
                longest_end = current;
            }
        }
    }

    if ( found )
    {
        if ( longest_end - longest_start < current - start )
        {
            longest_start = start;
            longest_end = current;
        }
    }

   if ( longest_start != longest_end )
   {        
        memmove( longest_start, longest_end, ( a + n - longest_end ) * sizeof( *a ) );
   }        

    n -= longest_end - longest_start;

    return n;
}

int main( void ) 
{
    int arr[] = { 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, };
    size_t n = sizeof( arr ) / sizeof( *arr );

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", arr[i] );
    printf( "\n" );

    n = longestsequence( arr, n );

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", arr[i] );
    printf( "\n" );
}    

程序输出

0 0 1 1 1 0 0 0 0 1 1 
0 0 1 1 1 1 1