题目一: 准备生日礼物 100分

张开发
2026/4/18 18:18:27 15 分钟阅读

分享文章

题目一: 准备生日礼物 100分
限制1s 空间限制256MB 限定语言C(clang11), C(clang11).Java(javac 1.8), Python3(3.9), JavaScript Node(12.18.2), Go(1.14.4), Rust(1.44)题目描述小明在一个充满人文关怀的公司上班公司每个月都要为该月生日的同事送一份生日小礼物该事项由小明负责请帮助小明统计某一月份应该准备多少礼物重复录入的员工生日以最后一次录入结果为准请不要重复统计避免浪费。输入参数1要发放礼物的月份取值1到12。参数2员工列表。参数3员工生日日期列表该列表和员工列表中的数据对应存在一一对应关系长度一致。输出该月份要准备的礼品个数。补充说明1小明公司的员工人数不超过100人。2员工姓名是字母和数字的组合姓名长度大于0小于16字节。3日期录入格式统一采用Year/Month/Day,Year长度为4,Month和Day长度为1到2系统保证录入日期为合法日期。4不考虑同名多位员工的情况名字一致即可认为是同一员工在生产系统会通过工号区分本系统简化处理。统计某月份生日员工数量的解决方案问题分析需要统计指定月份过生日的员工数量并处理重复录入的员工生日信息。重复录入时以最后一次记录为准。解决思路使用哈希表或字典存储员工姓名和生日信息自动处理重复记录遍历员工列表将每个员工及其生日存入哈希表统计哈希表中生日月份等于目标月份的员工数量C实现#include unordered_map #include string #include vector using namespace std; int countBirthdayGifts(int month, vectorstring employees, vectorstring birthdays) { unordered_mapstring, string employeeMap; for (int i 0; i employees.size(); i) { employeeMap[employees[i]] birthdays[i]; } int count 0; for (auto pair : employeeMap) { size_t firstSlash pair.second.find(/); size_t secondSlash pair.second.find(/, firstSlash 1); int birthMonth stoi(pair.second.substr(firstSlash 1, secondSlash - firstSlash - 1)); if (birthMonth month) { count; } } return count; }Java实现import java.util.HashMap; import java.util.Map; public class BirthdayCounter { public static int countBirthdayGifts(int month, String[] employees, String[] birthdays) { MapString, String employeeMap new HashMap(); for (int i 0; i employees.length; i) { employeeMap.put(employees[i], birthdays[i]); } int count 0; for (Map.EntryString, String entry : employeeMap.entrySet()) { String[] dateParts entry.getValue().split(/); int birthMonth Integer.parseInt(dateParts[1]); if (birthMonth month) { count; } } return count; } }JavaScript实现function countBirthdayGifts(month, employees, birthdays) { const employeeMap {}; for (let i 0; i employees.length; i) { employeeMap[employees[i]] birthdays[i]; } let count 0; for (const [_, birthday] of Object.entries(employeeMap)) { const birthMonth parseInt(birthday.split(/)[1]); if (birthMonth month) { count; } } return count; }Go实现package main import ( strconv strings ) func countBirthdayGifts(month int, employees []string, birthdays []string) int { employeeMap : make(map[string]string) for i, employee : range employees { employeeMap[employee] birthdays[i] } count : 0 for _, birthday : range employeeMap { parts : strings.Split(birthday, /) birthMonth, _ : strconv.Atoi(parts[1]) if birthMonth month { count } } return count }关键点说明使用哈希表自动处理重复员工记录日期解析统一采用字符串分割方式时间复杂度为O(n)空间复杂度为O(n)各语言实现逻辑相同仅语法差异这些实现都能正确处理重复员工记录并准确统计指定月份的生日员工数量。

更多文章