题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
大体思路是
先将输入数据保存在Map集合之中,
如果有重复的就重新给该元素赋值,
同时使用数组保存输入数据的key也就是Index的值,
通过排序数组,依次获取map中保存元素的值。
public static void main(String[] args) throws Exception{ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); HashMap<Integer,Integer> map = new HashMap<>(); int [] arr = new int[n]; for(int i = 0;i < n;i++){ arr[i] = -1; } while(n > 0){ n--; int index = scan.nextInt(); int value = scan.nextInt(); if(!map.containsKey(index)){ map.put(index,value); arr[n] = index; }else{ map.put(index,value + map.get(index)); } } Arrays.sort(arr); for(int i : arr){ if(i == -1) continue; System.out.println(i + " " + map.get(i)); } }