题目349:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2,
2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
分析349(简单-易理解):
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//给定两个数组,求出两者交互的部分,其中返回其中结果不包含重复值,对顺序不做要求
//思路:使用两个set来求,一个参考集,一个作为结果集
HashSet<Integer> set1=new HashSet<Integer>();
HashSet<Integer> set2=new HashSet<Integer>();
//参考集合
for(int i=0;i<nums1.length;i++){
set1.add(nums1[i]);
}
//查找结果集
for(int i=0;i<nums2.length;i++){
if(set1.contains(nums2[i])){
set2.add(nums2[i]);
}
}
//将结果集合转成数组
int [] res=new int[set2.size()];
int count=0;
for(int n:set2){
res[count++]=n;
}
return res;
}
}
分析349(参考答案):
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//求两个数组中相同的数,不包含重复值
//参考答案
//思路:利用两个数组实现Set的作用,分别标记1和2来实现不添加重复元素
int max = 0;
for (int i = 0; i < nums1.length; i++) {
max = Math.max(max, nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
max = Math.max(max, nums2[i]);
}
int[] arr = new int[max + 1];
for (int i = 0; i < nums1.length; i++) {
int n = nums1[i];
arr[n] = 1;
}
int count = 0;
for (int i = 0; i < nums2.length; i++) {
int n = nums2[i];
if(arr[n] == 1) {
//更改2的作用是再次不在添加相同的数据
arr[n] = 2;
count++;
}
}
int[] result = new int[count];
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 2) {
//分别给数据赋值
result[--count] = i;
}
}
return result;
}
}
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2,
2]
, return [2, 2]
.
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
//类似347,只是这次允许重复数据
//要求:数据有序,nums1的长度小nums2的长度,nums2的数据在硬盘中,不内存不允许将所有数据取出
//思路:使用HashMap来存储nums1的所有元素,通过计数来判断nums1的参考元素是否用完,用完则结束匹配
int count=nums1.length;
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<nums1.length;i++){
//将元素存入
hm.put(nums1[i],hm.getOrDefault(nums1[i],0)+1);
}
for(int i=0;i<nums2.length&&count>0;i++){
if(hm.containsKey(nums2[i])&&hm.get(nums2[i])>0){
hm.put(nums2[i],hm.get(nums2[i])-1);
//记录该元素
list.add(nums2[i]);
count--;
}
}
//返回结果
int i=0;
int [] res=new int[list.size()];
for(int n:list){
res[i++]=n;
}
return res;
}
}