Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
来源:互联网 发布:天刀太白少女捏脸数据 编辑:程序博客网 时间:2024/05/02 04:48
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解
// 有问题可以新浪微博@MebiuWpublic 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]
0 0
- Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
- 【LeetCode】Intersection of Two Arrays 解题报告
- [leetcode] 349. Intersection of Two Arrays 解题报告
- LeetCode 349. Intersection of Two Arrays 解题报告
- LeetCode解题报告 349. Intersection of Two Arrays [easy]
- [Leetcode] 349. Intersection of Two Arrays 解题报告
- [leetcode] 350. Intersection of Two Arrays II 解题报告
- 【LeetCode】Intersection of Two Arrays II 解题报告
- [Leetcode] 350. Intersection of Two Arrays II 解题报告
- leetcode 349. Intersection of Two Arrays python
- [leetcode: Python]349. Intersection of TWO Arrays
- leetcode 349. Intersection of Two Arrays-[Java]
- [python][leetcode]Intersection of Two Arrays II
- Leetcode-Intersection of Two Arrays-Python
- Leetcode 350. Intersection of Two Arrays II 数组交集2 解题报告
- [LeetCode] Intersection of Two Arrays(java)
- [LeetCode]Intersection of Two Arrays II(Java)
- [LeetCode-349] Intersection of Two Arrays(java)
- 毛主席箴言
- codeforces_667B. Coat of Anticubism
- HOJ 2713 Matrix1
- 贪心-hdu_1050_Moving Tables
- 非递归遍历二叉树
- Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
- 怎样制作基于Cocos2d-x的SLG游戏-第2章
- 从自我学习到深层网络
- LeetCode 334. Increasing Triplet Subsequence
- 对于MVC的认识
- 百度编辑器Editor 1.4.3.2 asp.net版最新使用方法
- 【C++】:C++之C++的引用
- day02-scala
- plist文件读取