此题如果直接使用有序的TreeMap就不需要这样折腾:
1.map的key值唯一性,故就不在需要set集合来去重
2.使用map后利用key的唯一性,把序列号相同的数据直接加在一起,代码会很简洁
package com.pagination.plus.workTrain;
import com.alibaba.fastjson.JSON;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class Main3 {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileInputStream("D:\JavaData\tmp/input.txt"));
//Scanner in = new Scanner(System.in);
while (in.hasNext()) {//注意while处理多个case
String strNum = in.nextLine();
int count = Integer.parseInt(strNum);
int[] k = new int[count];
int[] v = new int[count];
for (int i = 0; i < count; i++) {
String[] value = in.nextLine().split(" ");
//System.out.println(JSON.toJSONString(value));
k[i] = Integer.parseInt(value[0]);
v[i] = Integer.parseInt(value[1]);
}
Set<Integer> set = new HashSet<>();//相同的索引值只统计一次
Map<Integer,Integer> contents = new HashMap<>();//便于排序后输出
List<Integer> key = new ArrayList<>();
//List<Integer> val = new ArrayList<>();
//Map<Integer,Integer> map00 = new TreeMap<>();
for (int i = 0; i < count; i++) {
if (set.add(k[i])) {
int tmpVal = v[i];
for (int j = 0; j < count; j++) {
if ((i != j) && (k[i] == k[j])) {
tmpVal += v[j];
}
}
key.add(k[i]);
//val.add(tmpVal);
contents.put(k[i],tmpVal);
//map00.put(k[i],tmpVal);
//System.out.println(k[i] + " " + tmpVal);
}
}
//或者使用有序的TreeMap
//System.out.println(JSON.toJSONString(map00));
//排序
key.sort(Integer::compareTo);
//key.forEach(System.out::print);
for(int i=0;i<key.size();i++){
int index = key.get(i);
System.out.println(index+" "+contents.get(index));
}
}
}
}