[英]find and then delete the longest occurring sequence of 0 in an array
我的數組只有 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;
}
如果我正確理解了賦值,那么該函數可以如下所示,如下面的演示程序所示。 至少可以作為自己函數的基礎
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.