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.
求两个集合的交集 结果元素必须唯一
C++(6ms):
1 class Solution { 2 public: 3 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 4 unordered_set<int> s(nums1.begin(),nums1.end()) ; 5 vector<int> ans ; 6 for (int i = 0; i < nums2.size();i++ ){ 7 if(s.count(nums2[i])){ 8 ans.push_back(nums2[i]) ; 9 s.erase(nums2[i]); 10 } 11 } 12 return ans; 13 } 14 };
java(5ms):
1 class Solution { 2 public int[] intersection(int[] nums1, int[] nums2) { 3 Set<Integer> set = new HashSet<>() ; 4 for(int i = 0 ; i < nums1.length ; i++){ 5 set.add(nums1[i]) ; 6 } 7 List<Integer> list = new ArrayList<>() ; 8 for(int i : nums2){ 9 if (set.contains(i)){ 10 list.add(i) ; 11 set.remove(i) ; 12 } 13 } 14 int[] res = new int[list.size()] ; 15 for(int i = 0 ; i < list.size() ; i++){ 16 res[i] = list.get(i) ; 17 } 18 return res ; 19 } 20 }