Intersection of Arrays
Total Accepted: 5682 Total Submissions: 12479 Difficulty: Easy
Given the 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 is unique.
- The result can be on any order.
Subscribe to see which companies asked this question
Hide TagsBinary Search Hash Table pointers SortHide Similar Problems(E) intersection of Arrays II
Java code:
public class Solution {public int[] intersection (int[] nums1, int[] nums2) { int len1 = NUMS1.LENGTH,LEN2 = Nums2 . length; set<integer> set = new Hashset<integer> (); set<integer> interset = new hashset<integer> (); for (int i=0;i<len1;i++) { set.add (nums1[i]); } for (int i=0;i<len2;i++) { if (Set.contains (nums2[i))) Interset.add (Nums2[i]); } int[] ret = new int[interset.size ()]; int cnt = 0; for (int num:interset) { ret[cnt++] = num; } return ret; }}
Leetcode:intersection of Arrays