350. 两个数组的交集 II 简单 883 company 亚马逊 company 字节跳动 company Facebook 给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。
classSolution: defcontainsNearbyDuplicate(self, nums: List[int], k: int) -> bool: hash_1 = {} hash_2 = {} for index, i inenumerate(nums): if i notin hash_1: hash_1[i] = 1 hash_2[i] = [index] else: hash_1[i] += 1 hash_2[i].append(index) for i in hash_1: if hash_1[i] >= 2: for j inrange(len(hash_2[i])): for m inrange(j + 1, len(hash_2[i])): ifabs(hash_2[i][j] - hash_2[i][m]) <= k: returnTrue returnFalse
1 2 3 4 5 6 7 8 9 10 11 12
# 整理题意:是否存在长度不超过的 k+1k + 1k+1 窗口,窗口内有相同元素。 class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: n = len(nums) s = set() for i in range(n): if i > k: s.remove(nums[i - k - 1]) if nums[i] in s: return True s.add(nums[i]) return False