两个数组的交集
第一次尝试
思路
将第一个数组中的数字作为键,出现次数作为值统计出来,然后便利第二个数组,如果获取到的值是大于0的,说明第一个数组中出现了,然后将这个数加到结果集里面,将第一个数组出现的次数减一
代码
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map = new HashMap<>();
for (int i : nums1) {
map.put(i,map.getOrDefault(i,0) + 1);
}
List<Integer> ops = new ArrayList<>();
for (int i = 0; i < nums2.length; i++) {
Integer orDefault = map.getOrDefault(nums2[i], 0);
if (orDefault > 0) {
map.put(nums2[i],orDefault-1);
ops.add(nums2[i]);
}
}
return ops.stream().mapToInt(val->val).toArray();
}
}
提交结果
小结
才12.32%,速度是如此的慢,看来要想办法提高速度,想到前面做的几道题,每次使用Java Stream速度都很慢,这里能否可以使用数组代替了。
第二次尝试
思路
将结果集换成数组,不用列表,然后最后使用Stream转换为int数组
代码
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map = new HashMap<>();
for (int i : nums1) {
map.put(i,map.getOrDefault(i,0) + 1);
}
int index = 0;
int[] arr = new int[nums2.length];
for (int j : nums2) {
Integer orDefault = map.getOrDefault(j, 0);
if (orDefault > 0) {
map.put(j, orDefault - 1);
arr[index++] = j;
}
}
return Arrays.copyOf(arr,index);
}
}
提交结果
小结
这里可以看出,Stream实在太慢,以后算法题最好不要用了,哈哈哈,因为没有用stream,速度提升了50%
第三次尝试
思路
首先对两个数组进行排序,然后使用两个指针遍历两个数组,两个数组各一个下标指针,数值小的需要往后移动下标,直到两个数组取到的值相等,将这个数字加入到结果集中
代码
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] array = new int[Math.min(nums1.length,nums2.length)];
int index = 0,index1 = 0,index2 = 0;
while (index1 < nums1.length && index2 < nums2.length) {
if (nums1[index1] < nums2[index2]) {
index1++;
} else if (nums1[index1] > nums2[index2]) {
index2++;
} else {
array[index++] = nums1[index1];
index1++;
index2++;
}
}
return Arrays.copyOf(array,index);
}
}
提交结果
小结
速度大大提升了
总结
1.Stream 不能用了,实在是太慢了
2.能用数组就不要用列表
burybell@163.com