华为机考题解5 | #合并表记录#

合并表记录

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
          // 注意 hasNext 和 hasNextLine 的区别
        Scanner in = new Scanner(System.in);
        int zero=in.nextInt();
        Map<Integer,String> strMap=new TreeMap<>();
        while (zero<0) { // 注意 while 处理多个 case
            String a = in.nextLine();
            if(null==a||a.length()<=0){
                continue;
            }
            String[] z =a.split(" ");
            int key=Integer.parseInt(z[0].trim());
            int value=Integer.parseInt(z[1].trim());
            if(null!=strMap.get(key)){
                int oldVal=Integer.parseInt(strMap.get(key));
                strMap.put(key,String.valueOf(oldVal+value));
            }else{
                strMap.put(key,String.valueOf(value));
            }
           zero--;
        }
        strMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.   Entry::getValue,
                        (e1, e2) -> e1, TreeMap::new));
        strMap.entrySet().stream().forEach(e->{
            System.out.println(e.getKey()+" "+e.getValue());
        });
    }
}

以下是推荐方法:

import java.util.*;

public class Main {

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

TreeMap<Integer,Integer> map = new TreeMap<>();

while(sc.hasNext()){

int n = sc.nextInt();

for(int i =0;i<n;i++){

int key = sc.nextInt();

int value = sc.nextInt();

map.put(key,map.getOrDefault(key,0)+value);

}

for(Integer i : map.keySet()){

System.out.println(i+" "+map.get(i));

}

}

}

}

全部评论

相关推荐

霉国队长:多大本,只要GPA说得过去,那不随便藤校
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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