java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.youkuaiyun.com/grd_java/article/details/123063846 |
---|
解题思路 |
---|
- 创建一个记录容器A。我们可以先将第一个数组的元素,去重后,放入A。
- 然后判断第二个数组,如果它的元素,A中已经存在,那么这个元素就是交集。
- 每个交集元素,只输出一次
代码:使用set集合:时间复杂度O(m + n) 空间复杂度O(m + n),使用数组:时间复杂度O(m+n) 空间复杂度O(value) 其中value是数组中元素的取值范围 |
---|
class Solution {
//此方法,是用效率更好的数组索引,来代替Map,Set等Collection集合。效率当然更好,但是实际工作场景中,意义不大,只限做题时用
public int[] intersection(int[] nums1, int[] nums2) {
boolean[] map = new boolean[1001];//用数组充当map
ArrayList<Integer> list = new ArrayList<>();//用list充当set集合
for(int num:nums1) map[num] = true;//将nums1数组出现的元素,对应到map赋值为true
for(int num:nums2){//对nums2数组出现的元素
if(map[num]){//如果nums1也出现过
list.add(num);//将其添加到list中
map[num] = false;//相当于去重,下次再语句相同的元素,不再次添加到list
}
}
// return list.stream().mapToInt(i->i).toArray();
// return list.stream().mapToInt(Integer::intValue).toArray();
//上面注释掉的两行,是Java的stream流API + lambda表达式的两种写法。和下面的代码效果相同。但是上面两行有更多的健壮性考虑,是java自己提供的方法。
int[] res=new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i]= list.get(i);
}
return res;
}
/**
此方法,是直接用两个Set集合,而不用数组,效率肯定没有直接数组快,但是更加保险,也没有很大的局限性。是工作场景中的首选,工作场景中,上面那种效率更高的方法,是不可以使用的,很容易出现各种各样的问题,也很容易导致大量内存空间的浪费。
*/
public int[] intersection1(int[] nums1, int[] nums2) {
//除了中间容器换为set以外,其它操作没什么不同
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for (int num : nums1) {//先将nums1的元素放入set1,set会自动去重
set1.add(num);
}
for (int num : nums2) {//将nums2元素放入set2
set2.add(num);
}
return getIntersection(set1, set2);
}
public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
if (set1.size() > set2.size()) {//如果当前set2指向的集合更小
return getIntersection(set2, set1);//保证永远是set1比set2更小
}
Set<Integer> intersectionSet = new HashSet<Integer>();//保存答案
for (int num : set1) {//遍历set1的元素
if (set2.contains(num)) {//如果set2也有这个元素
intersectionSet.add(num);//将其添加到答案中
}
}
//将答案集合,转为int[]数组
int[] intersection = new int[intersectionSet.size()];
int index = 0;
for (int num : intersectionSet) {
intersection[index++] = num;
}
return intersection;
}
}