题解 | #合并表记录#

合并表记录

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

方法1:数组,简单,但浪费空间

import java.util.Scanner;

public class Main{
    public static int[] arr = new int[11111112];
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int flag = -1;
        for(int i = 1; i <= n; i++){
            
            int a = in.nextInt();
            int b = in.nextInt();
            arr[a] += b;
            
            
        }
        for(int i = 0; i < 11111112; i++){
            if(arr[i] != 0){
                System.out.println(i + " " + arr[i]);  
            }
            
        }
    }
    
}

方法2: hashmap

import java.util.*;

public class Main{
    
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0; i < n; i++){
            int a = in.nextInt();
            int b = in.nextInt();
            if(map.isEmpty() || !map.containsKey(a)){
                map.put(a,b);
            }
            else if(map.containsKey(a)){
                int temp = map.get(a);
                map.put(a,temp + b);
            }
        }
        //排序
        Set set = map.keySet();
        Object[] a1 = set.toArray();
        Arrays.sort(a1);
        
        for(Object key : a1){
            System.out.println(key + " " + map.get(key));
        }
        
    }
   
}
全部评论
第二种方案,TreeMap了解一下
点赞 回复 分享
发布于 2022-06-08 17:13

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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