All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : July 02, 2024
Last updated : July 02, 2024
Related Topics : Array, Hash Table, Two Pointers, Binary Search, Sorting
Acceptance Rate : 58.74 %
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> cnt1 = new HashMap<>();
HashMap<Integer, Integer> cnt2 = new HashMap<>();
for (int i : nums1) {
cnt1.put(i, cnt1.getOrDefault(i, 0) + 1);
}
for (int i : nums2) {
cnt2.put(i, cnt2.getOrDefault(i, 0) + 1);
}
ArrayList<Integer> output = new ArrayList<>();
for (Integer i : cnt1.keySet()) {
for (int j = 0; j < Integer.min(cnt1.get(i), cnt2.getOrDefault(i, 0)); j++) {
output.add(i);
}
}
int[] outputArr = new int[output.size()];
for (int i = 0; i < output.size(); i++) {
outputArr[i] = output.get(i);
}
return outputArr;
}
}
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> cnt = new HashMap<>();
for (int i : nums1) {
cnt.put(i, cnt.getOrDefault(i, 0) + 1);
}
ArrayList<Integer> output = new ArrayList<>();
for (int i : nums2) {
if (cnt.getOrDefault(i, 0) > 0) {
cnt.put(i, cnt.get(i) - 1);
output.add(i);
}
}
int[] outputArr = new int[output.size()];
for (int i = 0; i < output.size(); i++) {
outputArr[i] = output.get(i);
}
return outputArr;
}
}
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
cnt = Counter(nums1) & Counter(nums2)
output = []
for i, val in cnt.items() :
output.extend([i] * val)
return output