题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
审题结束后,首先想到的就是用dictionary来存储结果 首先创建一个list用来临时存储每次用户输入的数据 通过检查字典的key值 如果没有就加入字典,如果寂静存在了就将这个key的value加上新输入的value 排序这里利用了c#自带的linq来解决
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppTest
{
public static class Test
{
public static void Main()
{
int count = Convert.ToInt32(Console.ReadLine());
List<string> charList = new List<string>();
Dictionary<int,int> map = new Dictionary<int,int>();
for (int i = 0; i < count; i++)
{
charList = Console.ReadLine().Split(' ').ToList();
int key = Convert.ToInt32(charList[0]);
int value = Convert.ToInt32(charList[1]);
if (!map.ContainsKey(key))
{
map.Add(key, value);
}
else
{
map[key] = map[key] + value;
}
}
Dictionary<int,int> mapSorted = map.
OrderBy(x => x.Key).
ToDictionary(x =>x.Key,y=>y.Value);
foreach (var result in mapSorted)
{
Console.WriteLine("{0} {1}", result.Key, result.Value);
}
}
}
}