LintCode python 小白-简单题-548两数组的交Ⅱ
来源:互联网 发布:java sleep释放锁吗 编辑:程序博客网 时间:2024/06/11 09:28
题目:计算两个数组的交
注意事项
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出
样例: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
阅读全文
1 0
- LintCode python 小白-简单题-548两数组的交Ⅱ
- Lintcode python之两数组的交
- LintCode 548 两数组的交 II
- lintcode 548 两数组的交2
- LintCode 两数组的交Ⅱ
- LintCode:两数组的交
- LintCode:两数组的交
- 两数组的交-LintCode
- lintcode 两数组的交
- LintCode-两数组的交
- Lintcode 两数组的交
- LintCode 两数组的交
- LintCode(两数组的交)
- 两数组的交-LintCode
- lintcode 547两数组的交 lintcode 548两数组的交II
- lintcode 刷题-两数组的交 II Python
- LintCode(easy)两数组的交
- LintCode:两数组的交 II
- 20170730学习笔记之泛型
- Map集合中value()方法与keySet()、entrySet()区别
- 51nod1070(Bash游戏V4)
- mq-3-amq连接
- 几种TCP连接中出现RST的场景分析
- LintCode python 小白-简单题-548两数组的交Ⅱ
- Spring Boot 集成jsp、tomcat 时快时慢
- XYNU OJ 1101: 例题6-3 冒泡排序
- linux基本命令及操作10(虚拟机管理)
- 强制清除 gradle 依赖缓存
- 框架学习之struts2-01主要配置
- 爬虫实战6—分布式系统设计
- 西西里1007
- 利用 Jekyll + Github pages 搭建个人博客