350. Intersection of Two Arrays II
JAVA
class Solution { public int[] intersect(int[] nums1, int[] nums2) { Map<Integer, Integer> counter = new HashMap<>(); for (int num : nums1) { counter.put(num, counter.getOrDefault(num, 0) + 1); } List<Integer> t = new ArrayList<>(); for (int num : nums2) { if (counter.getOrDefault(num, 0) > 0) { t.add(num); counter.put(num, counter.get(num) - 1); } } int[] res = new int[t.size()]; for (int i = 0; i < res.length; ++i) { res[i] = t.get(i); } return res; } }
C++
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> counter; for (int num : nums1) ++counter[num]; vector<int> res; for (int num : nums2) { if (counter[num] > 0) { --counter[num]; res.push_back(num); } } return res; } };
Comments
Post a Comment