【华为机试】—— 8.合并表记录

题目

解法

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

public class Main {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        TreeMap<Integer, Integer> map = new TreeMap<>();
        
        int num = sc.nextInt();
        
        for(int i=0;i<num;i++){
            
            int key = sc.nextInt();
            int value = sc.nextInt();
            
            if(map.containsKey(key)){
                map.replace(key, map.get(key) + value);
            }else {
                map.put(key, value);
            }
            
        }
        
        for(Entry<Integer, Integer> entry: map.entrySet()){
            System.out.print(entry.getKey() + " ");
            System.out.println(entry.getValue());
        }
        
    }
}
原文地址:https://www.cnblogs.com/bopo/p/9259004.html