Intersection of Two Arrays II – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Explanation: [9,4] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
C++ Intersection of Two Arrays II LeetCode Solution
class Solution {// Using Map & without sort
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
map<int,int>freq;
vector<int>ans;
for(int i = 0;i<nums1.size();i++){
freq[nums1[i]]++;
}
for(int i = 0;i<nums2.size();i++){
if (freq[nums2[i]] > 0){
freq[nums2[i]]--;
ans.push_back(nums2[i]);
}
}
return ans;
}
};
Java Intersection of Two Arrays II LeetCode Solution
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i : nums1){
int freq = map.getOrDefault(i, 0);
map.put(i, freq + 1);
}
ArrayList<Integer> list = new ArrayList<>();
for(int i : nums2){
if(map.get(i) != null && map.get(i) > 0){
list.add(i);
map.put(i, map.get(i) - 1);
}
}
int[] ret = new int[list.size()];
for(int i = 0; i < list.size();i++){
ret[i] = list.get(i);
}
return ret;
}
Python 3 Intersection of Two Arrays II LeetCode Solution
class Solution(object):
def intersect(self, nums1, nums2):
nums1, nums2 = sorted(nums1), sorted(nums2)
pt1 = pt2 = 0
res = []
while True:
try:
if nums1[pt1] > nums2[pt2]:
pt2 += 1
elif nums1[pt1] < nums2[pt2]:
pt1 += 1
else:
res.append(nums1[pt1])
pt1 += 1
pt2 += 1
except IndexError:
break
return res
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1