您的位置:首页 > 编程语言 > Python开发

LintCode python 小白-简单题-548两数组的交Ⅱ

2017-07-30 15:00 357 查看
题目:计算两个数组的交

注意事项

每个元素出现次数得和在数组里一样

答案可以以任意顺序给出

样例:nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].

该知识可以直接解决lintCode的547 的问题:

获取两个list的交集:list(set(a).intersection(set(b)))

获取两个list的并集:list(set(a).union(set(b)))

获取两个list的差集:list(set(a).difference(set(b)))

思路:这道题我换了很多种思路,一直在80多%出现TLE。

下面的思路就不会,主要是先将两个列表进行排序,因为根据答案可以以任意顺序给出,所以排完序,进行比较,是否相等情况,这里主要要点在:什么时候列表的下表+1,得到下一个元素。

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
if nums1 == None or nums2 == None:
return []
nums1.sort()
nums2.sort()
nums = []
i = 0
j = 0
while i < len(nums1) and j < len(nums2):
if  nums1[i] ==nums2[j]:  #相等,添加到nums列表
nums.append(nums1[i])
i += 1
j += 1
else:
if nums1[i] > nums2[j]: #若1大于2,证明2要到下一个,否则1下一个
j+=1
else:
i+=1
return nums
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: