LeetCode 350 [Intersection of Two Array II]
原題
計算兩個陣列的交
注意事項
每個元素出現次數得和在陣列裡一樣答案可以以任意順序給出
樣例
nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
解題思路
- 遍歷第一個陣列,構建hash map,計數
- 遍歷第二個陣列,如果存在在hash map而且個數大於零,加入res陣列
- 其他方法:先排序,兩根指標
完整程式碼
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
map = {}
for x in nums1:
if x not in map:
map[x] = 1
else:
map[x] += 1
res = []
for y in nums2:
if y in map and map[y] > 0:
res.append(y)
map[y] -= 1
return res
相關文章
- leetcode 350. Intersection of Two Arrays IILeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- [LeetCode] 3152. Special Array IILeetCode
- LeetCode-350-兩個陣列的交集 IILeetCode陣列
- [leetcode]remove-duplicates-from-sorted-array-iiLeetCodeREM
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- [LeetCode] 80. Remove Duplicates from Sorted Array IILeetCodeREM
- 421-Maximum XOR of Two Numbers in an Array
- Leetcode每日一題:992.sort-array-by-parity-ii(按奇偶排序陣列Ⅱ)LeetCode每日一題排序陣列
- Leetcode 231 Power of TwoLeetCode
- Leetcode 1 two sumLeetCode
- LeetCode | 1 Two SumLeetCode
- Leetcode Sort ArrayLeetCode
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode-1 Two SumLeetCode
- [LeetCode]1.Two SumLeetCode
- Leetcode 231. Power of TwoLeetCode
- python: leetcode - 1 Two SumPythonLeetCode
- Find Minimum in Rotated Sorted Array I & II
- Rotate Array@LeetCodeLeetCode
- leetcode-29. Divide Two IntegersLeetCodeIDE
- LeetCode-2 Add Two NumbersLeetCode
- Leetcode 21 Merge Two Sorted ListsLeetCode
- LeetCode: Two sum(兩數之和)LeetCode
- [LeetCode] 29. Divide Two IntegersLeetCodeIDE
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- 【Leetcode】1029. Two City SchedulingLeetCode
- leetcode 371. Sum of Two IntegersLeetCode
- LeetCode Kth Largest Element in an ArrayLeetCode
- LeetCode Patching Array All In OneLeetCode
- leetcode-90. Subsets IILeetCode
- Leetcode 40 Combination Sum IILeetCode
- Leetcode 213 House Robber IILeetCode
- LeetCode 1103[分糖果II]LeetCode
- LeetCode 21. Merge Two Sorted ListsLeetCode