题解 | #合并表记录#

合并表记录

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

    }
}
全部评论

相关推荐

头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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