Leetcode 350) Intersection of Two Arrays II
in Algorithms
My Solution
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> m = new HashMap<>();
for(int i=0;i<nums1.length;i++){
if(!m.containsKey(nums1[i])){
m.put(nums1[i],1);
}else{
m.put(nums1[i],m.get(nums1[i])+1);
}
}
List<Integer> l = new ArrayList<>();
for(int i =0;i<nums2.length;i++){
if(m.containsKey(nums2[i]) && m.get(nums2[i])!=0){
l.add(nums2[i]);
m.put(nums2[i],m.get(nums2[i])-1);
}
}
int[] res = new int[l.size()];
int ptr=0;
for(int i: l){
res[ptr] = i;
ptr++;
}
return res;
}
}
Other Solution
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int[] freq = new int[1000];
ArrayList<Integer> resultList = new ArrayList<>();
for(int i : nums2)
{
freq[i]++;
}
for(int i: nums1)
{
if(freq[i]>0)
{
freq[i]--;
resultList.add(i);
}
}
int[] result = new int[resultList.size()];
for(int i=0; i< resultList.size(); i++ ){
result[i]= resultList.get(i);
}
return result;
}
}