BiruLyu
7/28/2017 - 3:37 PM

## 349. Intersection of Two Arrays(#).java

``````public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
}
}
int[] result = new int[intersect.size()];
int i = 0;
for (Integer num : intersect) {
result[i++] = num;
}
return result;
}
}``````
``````public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1.length==0 || nums2.length==0)
return new int[0];
int[] result =  new int[nums1.length>nums2.length?nums2.length:nums1.length];

Arrays.sort(nums1);
Arrays.sort(nums2);

int i=0,j=0,k=0; // pointer in the array, res
while (i < nums1.length && j < nums2.length) {
int n1 = nums1[i];
int n2 = nums2[j];
if (n1 == n2) {
if (k ==0 || result[k-1] != n1)
result[k++] = n1;
i++;
j++;
} else if (n1 < n2) {
i++;
} else {
j++;
}
}
return Arrays.copyOfRange(result, 0, k);
}
}``````
``````public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
boolean[] exist = new boolean[10000];
List<Integer> list = new ArrayList<>();
for(int i = 0;i < nums1.length;i++){
exist[nums1[i]] = true;
}
for(int i = 0;i < nums2.length;i++){
if(exist[nums2[i]]){
exist[nums2[i]] = false;
}
}
int[] result = new int[list.size()];
for(int i = 0;i < list.size();i++){
result[i] = list.get(i);
}
return result;
}
}``````
``````public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//Set<Integer> set = new HashSet<Integer>(Arrays.asList(nums1));
//Set<Integer> set = new HashSet<Integer>(Arrays.asList(nums1));
Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> res = new HashSet<>();