LeetCode 349 | Intersection of Two Arrays | Solution Explained (Java)

preview_player
Показать описание
Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Running Time: O(N+M)
Space Complexity: O(N+M)

Always be pluggin:
Рекомендации по теме
Комментарии
Автор

very nice explaination and very nice code as well.

satyamgupta
Автор

Very nice explanation thankyou so much 🙏🏼🙏🏼🙏🏼

someshsahu
Автор

when using this solution my output is just [2].

Here is the solution I submitted on leetcode:

class Solution {
public int[] intersect(int[] nums1, int[] nums2) {

HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> intersect = new HashSet<>();

for(Integer i : nums1){
set1.add(i);
}
for(Integer i : nums2){
if(set1.contains(i)){
intersect.add(i);
}
}
int size = intersect.size();
int[] ans = new int[size];
int index = 0;

for(Integer i : intersect){
ans[index++] = i;
}

return ans;
}
}

kevinrodriguez