题目描述:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
解题思路:
排序,对比
代码如下:
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
index_1 = 0
index_2 = 0
inter = [] while index_1 < len(nums1) and index_2 < len(nums2):
if nums1[index_1] == nums2[index_2]:
inter.append(nums1[index_1])
index_1 += 1
index_2 += 1
elif nums1[index_1] < nums2[index_2]:
index_1 += 1
else:
index_2 += 1 return inter