您的位置:首页 > 编程语言 > Go语言

蓝桥杯--算法训练之ALGO-79 删除数组零元素

2018-03-07 18:41 393 查看

算法训练 删除数组零元素



【分析】CompactIntegers()函数传入的参数为:数组a[],数组的大小n。返回值为void,在函数内使用输出语句输出结果。
【实现】设置一个计数器用于计算数组中不为0的元素的个数,遍历输入的数组,当计数器不为0时候输出计数器数值并输出所有非0元素,否则只输出0。
【代码】评测通过的C++代码如下:
#include <iostream>
using namespace std;
void CompactIntegers(int a[],int n)
{
int count = 0;
for(int i=0;i<n;i++)
{
if(a[i]!=0)
{
count++;
}
}
cout << count << endl;
if(count!=0)
{
for(int i=0;i<n;i++)
{
if(a[i]!=0)
{
cout << a[i] << " ";
}
}
}
}
int main()
{
int n;
cin >> n;
int *a = new int
;
for(int i=0;i<n;i++)
{
cin >> a[i];
}
CompactIntegers(a,n);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: