题解 | #合并表记录#

合并表记录

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);
            }
        } 
    }
}

全部评论

相关推荐

真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务