给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
count1 = len(nums1)
count2 = len(nums2)
if count1==0 or count2==0:
return []
res = []
if count1 < count2:
for i in range(count1):
if nums1[i] in nums2:
res.append(nums1[i])
else:
for i in range(count2):
if nums2[i] in nums1:
res.append(nums2[i])
return list(set(res))
class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
set record(nums1.begin(),nums1.end());
set res;
for(int i=0;i(res.begin(),res.end());
}
};
问题&思路:
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
record = set(nums1)&set(nums2)
res = []
if len(nums1)<=len(nums2):
for i in record:
res.extend([i]*min(nums2.count(i),nums1.count(i)))
else:
for i in record:
res.extend([i]*min(nums2.count(i),nums1.count(i)))
return res
class Solution {
public:
vector intersect(vector& nums1, vector& nums2) {
map record;
vector res;
for(int i=0;i0){
res.push_back(nums2[i]);
record[nums2[i]]--;
}
return res;
}
};
问题&思路: