题目链接:https://leetcode-cn.com/problems/intersection-of-two-arrays/
这是自己使用HashMap包的第一个实践,写得有点烂,而且代码的复杂度也很高,算是初步接触哈希表吧,以后要是可以会改善的。
Line 21: error: incompatible types: Object cannot be converted to Integer
for(Integer i : table1.values()){
^
这次遇到的问题是因为不理解泛型的作用,如果初始化不指明泛型的话,那么哈希表里面的变量类型就是Object,而不是Integer。
import java.util.HashMap;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//两个不重复的value
//A有的key B要是也有, 就把这个key存入新表
//HashMap table1 = new HashMap();
HashMap<Integer,Integer> table1 = new HashMap();
HashMap<Integer,Integer> table2 = new HashMap();
HashMap<Integer,Integer> table3 = new HashMap();
for(int i = 0; i < nums1.length; i++){
if(!table1.containsValue(nums1[i])){
table1.put(i, nums1[i]);
}
}
for(int i = 0; i < nums2.length; i++){
if(!table2.containsValue(nums2[i])){
table2.put(i, nums2[i]);
}
}
for(Integer i : table1.values()){
if(table2.containsValue(i)){
table3.put(i, i);
}
}
int[] res = new int[table3.size()];
int index = 0;
for(Integer i : table3.values()){
res[index++] = i;
}
return res;
}
}
看了参考答案之后人都傻了,原来自己写的时候一直在考虑的“能不能不存储key”的问题可以用HashSet
这个包来解决,所以答案用这个包就是在解决这个问题,学到了。
参考答案:
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
int[] resArr = new int[resSet.size()];
int index = 0;
//将结果几何转为数组
for (int i : resSet) {
resArr[index++] = i;
}
return resArr;
}
}