java题目数据表记录包含表索引和数值
描述
输入描述:
先输入键值对的个数n(1 <= n <= 500)
然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
示例1
4 0 1 0 2 1 2 3 4
0 3 1 2 3 4
示例2
3 0 1 0 2 8 9
0 3 8 9
1 import java.io.*; 2 import java.util.*; 3 4 public class Main{ 5 public static void main(String[] args) throws Exception{ 6 Scanner sc = new Scanner(System.in); 7 TreeMap<Integer, Integer> map = new TreeMap<>(); 8 while(sc.hasNextInt()) { 9 int n = sc.nextInt(); 10 for(int i=0; i<n; i++) { 11 int key = sc.nextInt(); 12 int value = sc.nextInt(); 13 //getOrDefault方法返回给定键的值,如果没有与该键相关的值,那么将返回指定的默认值 14 //put(key,value) 插入指定key-value 15 map.put(key, map.getOrDefault(key,0) + value); 16 } 17 } 18 for(Integer i : map.keySet()) { 19 System.out.println(i + " " + map.get(i)); 20 } 21 } 22 }
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
TreeMap<Integer, Integer> map = new TreeMap<>();
while(sc.hasNextInt()) {
int n = sc.nextInt();
for(int i=0; i<n; i++) {
int key = sc.nextInt();
int value = sc.nextInt();
//getOrDefault方法返回给定键的值,如果没有与该键相关的值,那么将返回指定的默认值
//put(key,value) 插入指定key-value
map.put(key, map.getOrDefault(key,0) + value);
}
}
for(Integer i : map.keySet()) {
System.out.println(i + " " + map.get(i));
}
}
}