题解 | #合并表记录#

合并表记录

http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201

该说不说,C++解题真简单,直接搞个map就解决了,上代码:

#include <iostream>
#include <map>

int main() {
  int n = 0, key = 0, val = 0;
  std::map<int, int> m;
  
  std::cin >> n;
  while (std::cin >> key >> val) {
    m[key] += val;
  }
  
  for (auto& t : m) {
    std::cout << t.firse << " " << t.second << std::endl;
  }
  
  return 0;
}

Java也一样,搞个TreeMap就行, 上代码:

import java.util.Scanner;
import java.util.TreeMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = 0, key = 0, val = 0;
        TreeMap<Integer, Integer> m = new TreeMap<>();
        
        n = sc.nextInt();
        for (int i = 0; i < n; ++i) {
            key = sc.nextInt();
            val = sc.nextInt(); 
            m.put(key, m.getOrDefault(key, 0)+val);
        }
        
        for (Map.Entry<Integer, Integer> e : m.entrySet()) {
            System.out.println(e.getKey() + " " + e.getValue());
        }
    }
}
全部评论

相关推荐

神哥不得了:神哥来啦~自我评价和校园经历的话可以直接删了,从大厂暑期的话应该没有什么太多问题,应该是能拿到很多大厂面试机会的,就是在面试的时候表示的好一点就行,可以在面试前先把高频top 50的八股多巩固几遍,千万不要看那些假高频八股,这两个项目的话问题不是很大,应该能够帮你找到大厂实习的,算法的话一定要刷起来,因为大厂有些还是比较看重算法的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务