给定一个包含公司员工姓名的字符串数组arr[] 。假设在一个系统中一个接一个地输入姓名,任务是检查当前姓名是否是第一次输入。
例子:
Input: arr[] = {“geeks”, “for”, “geeks”}
Output:
No
No
Yes
Input: arr[] = {“abc”, “aaa”, “cba”}
Output:
No
No
No
方法:创建一个 unordered_set 来存储员工的姓名并开始遍历数组,如果当前姓名已经存在于集合中,则打印 Yes else 打印 No 并将其插入到集合中。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to insert the names
// and check whether they appear
// for the first time
void insertNames(string arr[], int n)
{
// To store the names
// of the employees
unordered_set set;
for (int i = 0; i < n; i++) {
// If current name is appearing
// for the first time
if (set.find(arr[i]) == set.end()) {
cout << "No\n";
set.insert(arr[i]);
}
else {
cout << "Yes\n";
}
}
}
// Driver code
int main()
{
string arr[] = { "geeks", "for", "geeks" };
int n = sizeof(arr) / sizeof(string);
insertNames(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to insert the names
// and check whether they appear
// for the first time
static void insertNames(String arr[], int n)
{
// To store the names
// of the employees
HashSet set = new HashSet();
for (int i = 0; i < n; i++)
{
// If current name is appearing
// for the first time
if (!set.contains(arr[i]))
{
System.out.print("No\n");
set.add(arr[i]);
}
else
{
System.out.print("Yes\n");
}
}
}
// Driver code
public static void main(String[] args)
{
String arr[] = { "geeks", "for", "geeks" };
int n = arr.length;
insertNames(arr, n);
}
}
// This code contributed by PrinciRaj1992
Python3
# Python3 implementation of the approach
# Function to insert the names
# and check whether they appear
# for the first time
def insertNames(arr, n) :
# To store the names
# of the employees
string = set();
for i in range(n) :
# If current name is appearing
# for the first time
if arr[i] not in string :
print("No");
string.add(arr[i]);
else :
print("Yes");
# Driver code
if __name__ == "__main__" :
arr = [ "geeks", "for", "geeks" ];
n = len(arr);
insertNames(arr, n);
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to insert the names
// and check whether they appear
// for the first time
static void insertNames(String []arr, int n)
{
// To store the names
// of the employees
HashSet set = new HashSet();
for (int i = 0; i < n; i++)
{
// If current name is appearing
// for the first time
if (!set.Contains(arr[i]))
{
Console.Write("No\n");
set.Add(arr[i]);
}
else
{
Console.Write("Yes\n");
}
}
}
// Driver code
public static void Main(String[] args)
{
String []arr = { "geeks", "for", "geeks" };
int n = arr.Length;
insertNames(arr, n);
}
}
// This code is contributed by Rajput-Ji
Javascript
输出:
No
No
Yes
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。