Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
2016-05-18 23:30
746 查看
1 解题思想
这道题就是说,求两个数组的交集,所以做法也很简单:使用哈希Set存入第一个数组的值
遍历第二个数组,如果第二个的数在Set中出现,那么就是交集(与此同时,因为只能返回一个值,所以出现后还需要从Set中删除哦)
2 原题
Given two arrays, write a function to compute their intersection.Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
3 AC解
// 有问题可以新浪微博@MebiuW public class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer> set = new HashSet<Integer>(); for(int i=0;i<nums1.length;i++) set.add(nums1[i]); //遍历增加 List<Integer> resultList = new ArrayList<Integer>(); for (int i=0;i<nums2.length;i++) if(set.contains(nums2[i])){ resultList.add(nums2[i]); set.remove(nums2[i]); //记得删除 } int result[] = new int[resultList.size()]; for(int i=0;i<resultList.size();i++) result[i]=resultList.get(i); return result; } }
4 AC 解 Python版
感觉用Python好简洁,喵class Solution(object): def intersection(self, nums1, nums2): result = list() for num in set(nums1) : if num in nums2: result.append(num) return result
5 再度更新个一句话版的
python的列表生成器,刚刚忙着赶,没用这个。。毕竟我对Python也不熟悉,只是知道有这个东西,喵class Solution(object): def intersection(self, nums1, nums2): return [num for num in set(nums1) if num in nums2]
相关文章推荐
- Python抽象工厂模式
- Python实现简单爬虫
- PYTHON 源码阅读
- 13. Roman to Integer [easy] (Python)
- python
- python 下字符串格式时间比较
- Python处理多个客户端连接---派生服务器
- Python 模块之间的调用
- 解决 Mac 上用 Pycharm 搭建 openCV 的 python 开发环境中的问题
- python反射
- Kivy python在ubuntu下安装使用
- Kivy python在ubuntu下安装使用
- python中%和format
- python静态网页爬虫之xpath
- The internals of Python string interning
- Java&Python操作WebHDFS
- Python dictionary implementation
- python中join和split函数
- [python爬虫]爬取贴吧某页美女图片+爬取糗百美女图片
- python3 下ascii与 str的转换