用C#实现:有一个party,有n个人参加,编号相同的人相互认识,请找到唯一的陌生人,例如输入:{3,3,8,3}输出:8,输入{5,6,7,7,7,6,7,7}输出5
时间: 2024-04-12 10:32:38 浏览: 16
你可以使用字典(Dictionary)来解决这个问题。下面是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] attendees = { 3, 3, 8, 3 };
int stranger = FindStranger(attendees);
Console.WriteLine("唯一的陌生人编号:" + stranger);
int[] attendees2 = { 5, 6, 7, 7, 7, 6, 7, 7 };
int stranger2 = FindStranger(attendees2);
Console.WriteLine("唯一的陌生人编号:" + stranger2);
}
static int FindStranger(int[] attendees)
{
Dictionary<int, int> countDict = new Dictionary<int, int>();
foreach (int attendee in attendees)
{
if (countDict.ContainsKey(attendee))
{
countDict[attendee]++;
}
else
{
countDict[attendee] = 1;
}
}
foreach (var pair in countDict)
{
if (pair.Value == 1)
{
return pair.Key;
}
}
return -1; // 如果没有陌生人则返回-1,可以根据实际情况修改
}
}
```
这段代码首先定义了一个字典 `countDict`,用于记录每个人出现的次数。然后遍历参加派对的人员,如果字典中已经存在该人员编号,则将其对应的值加1;如果字典中不存在该人员编号,则将其添加到字典中,并将其对应的值设为1。
接下来,再次遍历字典中的键值对,找到出现次数为1的键(即只出现一次的人员编号),并返回该编号作为唯一的陌生人。
运行代码后,你将获得输出结果:
```
唯一的陌生人编号:8
唯一的陌生人编号:5
```
这样你就成功找到了参加派对中唯一的陌生人的编号。