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
- 350. Intersection of Two Arrays II--LeetCode RecordLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- [leetCode][003] Intersection of Two Linked ListsLeetCode
- Leetcode-Intersection of Two Linked ListsLeetCode
- 349. Intersection of Two Arrays--LeetCode RecordLeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- 【Leetcode】160. Intersection of Two Linked ListsLeetCode
- Leetcode[421] Maximum XOR of Two Numbers in an ArrayLeetCode
- Median of Two Sorted Array leetcode javaLeetCodeJava
- Leetcode Search in Rotated Sorted Array IILeetCode
- LeetCode-Search in Rotated Sorted Array IILeetCode
- Leetcode Remove Duplicates from Sorted Array IILeetCodeREM
- Search in Rotated Sorted Array II leetcode javaLeetCodeJava
- 【LeetCode從零單排】No.160 Intersection of Two Linked ListsLeetCode
- LeetCode-350-兩個陣列的交集 IILeetCode陣列
- [leetcode]remove-duplicates-from-sorted-array-iiLeetCodeREM
- Leetcode-Remove Duplicates from Sorted Array IILeetCodeREM
- Remove Duplicates from Sorted Array II leetcode javaREMLeetCodeJava
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- Leetcode-Find Minimum in Rotated Sorted Array IILeetCode
- [LeetCode] 80. Remove Duplicates from Sorted Array IILeetCodeREM
- Leetcode Two SumLeetCode
- Leetcode Power of TwoLeetCode
- Leetcode每日一題:992.sort-array-by-parity-ii(按奇偶排序陣列Ⅱ)LeetCode每日一題排序陣列
- Leetcode 1 two sumLeetCode
- Leetcode-Two SumLeetCode
- Two Sum leetcode javaLeetCodeJava
- LeetCode | 1 Two SumLeetCode
- Leetcode Sort ArrayLeetCode
- [LeetCode]1.Two SumLeetCode
- LeetCode----1. Two SumLeetCode
- LeetCode 1.Two NumsLeetCode
- LeetCode1:Two SumLeetCode
- Leetcode Divide Two IntegersLeetCodeIDE
- Leetcode Add Two NumbersLeetCode
- [LeetCode]1. Two SumLeetCode