Problem Description:
1. The question involves knowledge points.
- Key-value pair type data sorting
Map
Use in key-value pair type data mergeTreeMap
.
2. Solve it yourself.
- Use a priority queue to store data, sorted according to the first element
- Traverse the mailbox queue and add two consecutive elements first.
package com.chaoxiong.niuke.huawei;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
/**
* Create by tianchaoxiong on 18-5-2.
*/
public class HuaWei_8_3 {
private int key1;
private int key2;
private int getKey1() {
return key1;
}
public int getKey2() {
return key2;
}
private HuaWei_8_3(int key1, int key2) {
this.key1 = key1;
this.key2 = key2;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Comparator<HuaWei_8_3>OrderIsdn = new Comparator<HuaWei_8_3>() {
@Override
public int compare(HuaWei_8_3 o1, HuaWei_8_3 o2) {
int a = o1.getKey1();
int b = o2.getKey1();
return Integer.compare(a, b);//从大到小
}
};
while (scanner.hasNextInt()){
int N = scanner.nextInt();
Queue<HuaWei_8_3>priorityQueue = new PriorityQueue<HuaWei_8_3>(2,OrderIsdn);
for(int i=0;i<N;i++){
HuaWei_8_3 huaWei_8_3 = new HuaWei_8_3(scanner.nextInt(),scanner.nextInt());
priorityQueue.add(huaWei_8_3);
}
// 做一个比较打印
int [][]intArr = new int[N][2];
int intArrIndex = 0;
while (priorityQueue.peek() != null) {
HuaWei_8_3 tmp = priorityQueue.poll();
int a1 = tmp.getKey1();
int a2 = tmp.getKey2();
if(intArrIndex==0){
intArr[intArrIndex][0] = a1;
intArr[intArrIndex][1] = a2;
intArrIndex++;
}else {
if(a1==intArr[intArrIndex-1][0]){
intArr[intArrIndex-1][0] = a1;
intArr[intArrIndex-1][1] = intArr[intArrIndex-1][1]+a2;
}else {
intArr[intArrIndex][0] = a1;
intArr[intArrIndex][1] = a2;
intArrIndex++;
}
}
}
//打印
for(int i=0;i<intArrIndex;i++){
System.out.println(intArr[i][0]+" "+intArr[i][1]);
}
}
}
}
3. Quality answers.
mport java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
/**
* Create by tianchaoxiong on 18-4-12.
* // 使用map
*/
public class HuaWei_8_4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
int N = scanner.nextInt();
Map<Integer,Integer> map= new TreeMap<Integer,Integer>();
for(int i=0;i<N;i++){
int key = scanner.nextInt();
int value = scanner.nextInt();
if(map.containsKey(key))
map.put(key,map.get(key)+value);
else map.put(key,value);
}
for(Integer key:map.keySet()){
System.out.println(key+" "+map.get(key));
}
}
}
}
4. Summary of this question.
In this question, I use a priority queue to store data. I use the orderly and non-unique characteristics of the priority queue.
When traversing again, I accumulate the same key2 of key1, which is more suitable for implementation with TreeMap.