任务描述:
去除数组中的重复数据。
具体要求如下:
接收给定的数据(如:4 88 43 43 98,其中第一个数代表数组长度,其余数代表数组元素;
创建数组并添加元素;
去除数组中重复元素。
测试输入:
(1) 4
(2) 6
(3) 6
(4) 6
(5) 7
预期输出:
(1) 6
(2) 7
(3)
以上红色数字为输入输出内容。注意:预期输出中最后有一行空行。
运行结果及代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string result = Console.ReadLine();
string[] nmbs = result.Split(' '); //用空格分割
int n = int.Parse(nmbs[0]);
int j = 1;
nmbs[0] = nmbs[1];
for (int i = 1; i < n; i++)
{
if (nmbs[i + 1].CompareTo(nmbs[i]) != 0)
{
nmbs[j++] = nmbs[i + 1];
}
}
//输出
for (int i = 0; i < j; i++)
Console.WriteLine(nmbs[i]);
}
}
}
以上红色数字为输入输出内容===看不到红色,都是黑色文字
定义一个数组,然后逐个字符与后面所有数字比较,记录比较的位置,每遇到一个不同的数字,则写入比较位置
#include <stdio.h>
int main()
{
int n,i,j,k,a[1000],cnt=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
k=i+1;
cnt = 0;
for(j=i+1;j<n;j++)
{
if(a[i] != a[j])
{
a[k] = a[j];
k++;
}
else
cnt++;
}
n -= cnt;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!