计算两个数组的交
注意事项
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出
样例
nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2, 2]
.
一开始:Time Limit Exceeded
class Solution:
# @param {int[]} nums1 an integer array
# @param {int[]} nums2 an integer array
# @return {int[]} an integer array
def intersection(self, nums1, nums2):
# Write your code here
'''
nums3=[]
if len(nums1)>=len(nums2):
for i in nums2:
if i in nums1:
nums1.remove(i)
nums3.append(i)
return nums3
else:
for i in nums1:
if i in nums2:
nums2.remove(i)
nums3.append(i)
return nums3
'''
if nums1 == None or nums2 == None:
return []
nums1 = sorted(nums1)
nums2 = sorted(nums2)
nums = []
i = 0
j = 0
while i < len(nums1) and j < len(nums2):
while i < len(nums1) and j < len(nums2) and nums1[i] < nums2[j]:
i += 1
while i < len(nums1) and j < len(nums2) and nums1[i] > nums2[j]:
j += 1
while i < len(nums1) and j < len(nums2) and nums1[i] == nums2[j]:
nums.append(nums1[i])
i += 1
j += 1
return nums