利用hashmap去重,在将ksySet排序
import java.util.*; /** * @author Shan * @create 2021-05-31 下午 8:02 */ public class Main { public static void main(String args[]) { Scanner scn=new Scanner(System.in); int num=Integer.parseInt(scn.nextLine()); HashMap<Integer,Integer> map=new HashMap<>(); while (scn.hasNext()){ for(int i=0;i<num;i++){ String[] str=scn.nextLine().split(" "); map.put(Integer.parseInt(str[0]),map.getOrDefault(Integer.parseInt(str[0]),0)+Integer.parseInt(str[1])); } List<Integer> list=new ArrayList<>(map.keySet()); Collections.sort(list); for(int k:list) System.out.println(k+" "+map.get(k)); } } }