判断一个数组中的数字是否连续

问题描述:一个数组中若干个非负整数是否连续,其中0可以代表任何数字

Input:

8

1 3 5 0 0 0 6 7

Output:

this array is continue


算法实现:

#include
using namespace std;


void sort(int* a,int m)
{
int temp=0;
for (int i=0;i{
for (int j=0;j{
if (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}


bool Fun(int* a,int m)
{
int sum=0,j=0;


for (int i=1;i{
if(a[i-1]!=0)
{
sum +=(a[i]-a[i-1]-1);
}
else
j++;
}
if(j >= sum)
return true;
else 
return false;

}
void main()
{
int m;
cout<<"m=";
cin>>m;
int *a = new int[m];


for (int i=0; i{
cin>> a[i];
}


for (int j=0;i{
cout<}


sort(a,m);
if(Fun(a,m))
{
cout<<"this array is continue!"<}
else
{
cout<<"is not continue!"<}
system("pause");
}



后来想了想觉得还是有漏洞,修改了一下


#include
using namespace std;


void sort(int* a,int m)
{
int temp=0;
for (int i=0;i{
for (int j=0;j{
if (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}


bool Fun(int* a,int m)
{
int sum=0,j=0;


for (int i=1;i{
if(a[i-1]!=0)
{
int temp = a[i]-a[i-1]-1;
if (temp>=0)
{
sum += temp;
}
else
return false;

}
else
j++;
}
if(j >= sum)
return true;
else 
return false;

}
void main()
{
int m;
cout<<"m=";
cin>>m;
int *a = new int[m];


for (int i=0; i{
cin>> a[i];
}


for (int j=0;i{
cout<}


sort(a,m);
if(Fun(a,m))
{
cout<<"this array is continue!"<}
else
{
cout<<"is not continue!"<}
system("pause");
}

你可能感兴趣的:(C++)