题解 | #合并表记录#

合并表记录

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

大体思路是 
先将输入数据保存在Map集合之中,
如果有重复的就重新给该元素赋值,
同时使用数组保存输入数据的key也就是Index的值,
通过排序数组,依次获取map中保存元素的值。

    public static void main(String[] args) throws Exception{
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        HashMap<Integer,Integer> map = new HashMap<>();
        int [] arr = new int[n];
        for(int i = 0;i < n;i++){
              arr[i] = -1;
        }
        while(n > 0){
            n--;
            int index = scan.nextInt();
            int value = scan.nextInt();    
            if(!map.containsKey(index)){
                map.put(index,value); 
                arr[n] = index;  
            }else{
                map.put(index,value + map.get(index));
            } 
            
        }
          Arrays.sort(arr);
          for(int i : arr){
              if(i == -1) continue;
              System.out.println(i + " " + map.get(i));
          }             
    }


全部评论
你好垃圾,还有脸发出来😥
点赞 回复 分享
发布于 2022-07-21 16:48

相关推荐

_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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