题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
//使用字典实现 using System; using System.Collections.Generic; using System.Linq; namespace HJ8{ class Solution{ public static void Main(){ int count = Convert.ToInt32(Console.ReadLine()); var res = new Dictionary<int, int>(); for(int i = 0; i < count; i++){ var charArray = Console.ReadLine().Split(' '); var tempIndex = Convert.ToInt32(charArray[0]); var tempValue = Convert.ToInt32(charArray[1]); if(res.ContainsKey(tempIndex)){//判断是否存在记录 1、有 相加值 2、无 添加记录 res[tempIndex] += tempValue; }else{ res.Add(tempIndex, tempValue); } } var orderedRes = res.OrderBy(x=>x.Key).ToDictionary(x=>x.Key,x=>x.Value);//按照Key值排序 foreach(var kvp in orderedRes){//遍历输出 Console.WriteLine("{0}"+" "+"{1}",kvp.Key,kvp.Value); } } } }