解法:由于同一个list中可能存在重复元素,所以考虑采用计数的方式解决问题,具体思路如下:
首先构建一个dict来记录list中的元素个数,称为count_dict;count_dict中的元素是一个长度为2的list,分别存储nums1和nums2中元素i的个数
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: count_dict = {} for i in nums1: if i not in count_dict: count_dict[i] = [1, 0] else: count_dict[i][0] += 1 for i in nums2: if i not in count_dict: # nums2中有但nums1中没有的元素,就没必要再做记录了 continue count_dict[i][1] += 1 result_list = [] for key in count_dict: # 遍历,统计某个元素i在nums1和nums2中出现次数的较小值num,若num不为0,则将num个元素i加入到结果list(result_list)中 num = min(count_dict[key]) if num: result_list += [key]*num return result_list
列表还支持拼接操作
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: count_dict = {} for i in nums1: if i not in count_dict: count_dict[i] = 1 new_arr = [] for i in nums2: if count_dict.get(i): new_arr.append(i) count_dict[i] -= 1 return new_arr
count_dict[i] -= 1是为了count_dict.get(i)判断用
如果不减1,就会出现重复
如:
nums1 = [4,9,5, 4]
nums2 = [9,4,9,8,4]