题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.valueOf(scan.nextLine().trim());
HashMap<Integer, Integer> hashMap = new HashMap<>();
HashSet<Integer> hashSet = new HashSet<>();
for (int i = 1; i <= n; i++) {
String str = scan.nextLine();
int index = Integer.valueOf(str.split(" ")[0].trim());
int currentVal = Integer.valueOf(str.split(" ")[1].trim());
int previousVal = hashMap.getOrDefault(index, 0);
hashMap.put(index, previousVal + currentVal);
hashSet.add(index);
}
ArrayList<Integer> arrayList = new ArrayList<>(hashSet);
int[] nums = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
nums[i] = arrayList.get(i);
}
heapSort(nums);
for (int num : nums) {
System.out.println(num + " " + hashMap.get(num));
}
}
public static void heapSort(int[] nums) {
if (null == nums || nums.length < 2) {
return;
}
for (int i = 0; i < nums.length; i++) {
heapInsert(nums, i);
}
int heapSize = nums.length;
swap(nums, 0, --heapSize);
while (heapSize > 0) {
heapify(nums, 0, heapSize);
swap(nums, 0, --heapSize);
}
}
public static void heapInsert(int[] nums, int index) {
while (nums[index] > nums[(index - 1) / 2]) {
swap(nums, index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
public static void heapify(int[] nums, int index, int heapSize) {
int left = index * 2 + 1;
while (left < heapSize) {
int largest = left + 1 < heapSize && nums[left + 1] > nums[left] ? left + 1 : left;
largest = nums[largest] > nums[index] ? largest : index;
if (largest == index) {
break;
}
swap(nums, index, largest);
index = largest;
left = index * 2 + 1;
}
}
public static void swap(int[] nums, int p1, int p2) {
int tmp = nums[p1];
nums[p1] = nums[p2];
nums[p2] = tmp;
}
}