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,得到下一个元素。
注意事项
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出
样例: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
相关文章推荐
- LintCode python 小白-简单题-569各位相加
- LintCode python 小白-简单题-2 尾部的0
- LintCode python 小白-简单题-457经典二分查找问题
- LintCode python 小白-简单题-22平面列表
- LintCode python 小白-简单题-413-反转整数
- LintCode python 小白-简单题-627最长回文串
- LintCode python 小白-简单题-445余弦相识度
- LintCode python 小白-简单题-646 First Position Unique Character
- Lintcode python之两数组的交
- LintCode python 小白5-丑数
- LintCode python 小白6-丑数 II
- LintCode python 小白4-Big Integer Addition
- LintCode python 小白7-超级丑数
- LintCode python 小白-硬币-博弈论,动态规划
- LintCode Python 101. 删除排序数组中的重复数字 II
- LintCode python 小白3-三角形计数
- LintCode -- 最大子数组 III
- python_lintcode_简单题 _44最小子数组_41最大子数组
- LintCode-数组剔除元素后的乘积
- lintcode之数组划分