题解 | #合并表记录#

合并表记录

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.nextLine();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            String s = in.nextLine();
            String[] str = s.split(" ");
            String sIndex = String.valueOf(str[0]);
            String sValue = String.valueOf(str[1]);
            int iIndex = Integer.parseInt(sIndex);
            int iValue = Integer.parseInt(sValue);
            if (i == 0) {
                map.put(iIndex, iValue);
            }
//如果存在相同的key
            else if (map.containsKey(iIndex)) {
                int a1 = map.get(iIndex);
                int a3 = a1 + iValue;
                map.put(iIndex, a3);
            } else {
                map.put(iIndex, iValue);
            }
        }
        Set<Integer> setKey = map.keySet();
        List<Integer> keys = new ArrayList<>(setKey);
        Collections.sort(keys);
        for (int key : keys) {
            System.out.println(key+" "+map.get(key));
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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