forked from Doragd/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
hash哈希哈希
Description
- 数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。
- 提示: 0 <= index <= 11111111 1 <= value <= 100000
- 递归遍历+问题分解+分类讨论
- 建立hashmap 遍历拿到同样key 的话
- getOrDefault 这个方法
- 记得相加 然后排序
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int input = in.nextInt();
if( 1 > input && input >500){
System.out.println("请重新录入,录入数值不正确");
}
//使用hashmap接受键值对
Map<Integer,Integer> mapIndex = new HashMap<>();
for(int i= 0 ; i<input;i ++){
int index = in.nextInt();
int value = in.nextInt();
mapIndex.put(index,mapIndex.getOrDefault(index,0) + value);
}
Map<Integer,Integer> sortSet = new TreeMap<>(mapIndex);
sortSet.forEach((k,v) ->System.out.println(k+" "+ v));
}
}
}Metadata
Metadata
Assignees
Labels
hash哈希哈希