题目一
题目描述:
题目二
题目描述:给定一个整数数组A,拥有N个不重复的整数。找到数组中两个数之和出现最多的和。如果有多种可能,输出全部结果(结果顺序任意)
输入格式:
第一行: N (数组个数)
第二行: N个空格分隔的整数
输出格式:
打印输出结果,多个结果多行显示
样本输入:
8
1 8 3 11 4 9 2 7
样本输出
11
10
12
package exam;
import java.util.HashMap;
import java.util.Scanner;
public class QushiAdd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
HashMap<Integer, Integer> addMap = new HashMap<>();
int temp;
int addMax = 0; // 出现最多次数的和
int numMax = Integer.MIN_VALUE; // 和出现最多的次数
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
temp = nums[i] + nums[j];
if (!addMap.containsKey(temp)) {
addMap.put(temp, 1);
if (numMax < 1) {
numMax = 1;
addMax = temp;
}
} else {
if (numMax < addMap.get(temp) + 1) {
numMax = addMap.get(temp) + 1;
addMax = temp;
}
addMap.put(temp, addMap.get(temp) + 1);
}
}
}
for (Integer key : addMap.keySet()) {
if (addMap.get(key) == numMax) {
System.out.println(key);
}
}
}
}
知识点总结
1.HashMap的遍历
- 映射没有实现Iterable接口,无法使用for-each循环遍历,但是可以获取映射的集合视图,集合视图允许使用for循环和迭代器。
- 使用 entrySet() 方法得到包含映射中元素的Set对象;
- 使用 keySet() 方法得到映射中所有键的集合视图
- 使用 values() 方法得到映射中所有值的集合视图
// HashMap遍历,通过键找值遍历(效率低)
for (Integer key : addMap.keySet()) {
if (addMap.get(key) == numMax) {
System.out.println(key);
}
}
// 遍历2, 当键和值都需要时使用
for(Map.Entry<Integer,Integer> entry:addMap.entrySet()){
if (entry.getValue()==numMax){
System.out.println(entry.getKey());
}
}
// 使用Iterator遍历
Iterator<Map.Entry<Integer,Integer>> entries=addMap.entrySet().iterator();
while (entries.hasNext()){
Map.Entry<Integer,Integer> entry=entries.next();
if (entry.getValue()==numMax){
System.out.println(entry.getKey());
}
}