题解 | 数组中只出现一次的两个数字
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param nums int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce(int[] nums) {
// write code here
HashMap<Integer, Integer> mp = new HashMap<>();
int[] ans = {-1, -1};
for (int k : nums) {
int count = 0;
if (mp.get(k) == null) {
mp.put(k, 1);
} else {
count = mp.get(k) + 1;
mp.put(k, count);
}
}
for (int num : nums) {
if (mp.get(num) == 1) {
// 其实这里使用List的push会简洁高效一点。// 使用Collections.sort()对列表进行升序排序
for (int j = 0; j < ans.length; ++j) {
if (ans[j] == -1) {
ans[j] = num;
break;
}
}
}
}
// Arrays.sort(ans, (x, y) -> (x - y));// int(基础数据类型)数组不能像这样自定义排序。因为java泛型不支持基础数据类型作为模版T
Arrays.sort(ans);
/*
// int数组转为Integer
Integer[] interArray = Arrays.stream(ans)
.boxed() // 将 int 转换为 Integer(装箱)
.toArray(Integer[]::new); // 转换为 Integer 数组
// 使用lambda,简洁
Arrays.sort(interArray, (x, y) -> x - y);
// 使用匿名函数,不太简洁:
// Arrays.sort(interArray, new Comparator<Integer>() {
// @Override
// public int compare(Integer x, Integer y) {
// return x - y;
// }
// });
// 使用Stream API将Integer数组转换为int数组
int[] intArray = Arrays.stream(interArray)
.filter(i -> i != null) // 过滤掉可能的null值
.mapToInt(Integer::intValue)//转换为 IntStream(基本类型流)
.toArray(); // 转换为数组
return intArray;
*/
return ans;
}
}
这题,不难,对语法足够熟悉就好。
如果出现的是升序排序的话,自定义比较器还是挺恶心的(刚开始用),得作类型转换。
查看24道真题和解析