分析:
是在求两个数组的交集元素,并且这个元素不能重复,用到哈希数组。
1.创建布尔类型的hash数组
2.遍历nums1,遍历到的元素用true标记
3.遍历nums2,判断nums2中的元素是否已经被标记过
如果被标记过,说明这个元素是两个数组的公共元素,放在ret中。重复的元素标记为false,防止重复添加。
public class Solution {
public ArrayList<Integer> intersection (ArrayList<Integer> nums1, ArrayList<Integer> nums2) {
//创建一个布尔类型的哈希数组,大小为1010
boolean[] hash = new boolean[1010];
//创建ret用来存放交集结果
ArrayList<Integer> ret = new ArrayList<>();
//遍历nums1,标记为true表明nums1中的元素在hash数组中存在过
for(int x : nums1){
hash[x] = true;
}
//遍历nums2,判断nums2中的元素是否被标记过
for(int x : nums2){
//如果该元素存在于hash数组中,说明是同时存在于nums1和nums2
if(hash[x]){
//将交集元素放在ret中
ret.add(x);
//防止重复添加
hash[x] = false;
}
}
return ret;
}
}