Leetcode:349. Intersection of Two Arrays
来源:互联网 发布:暖气片专用晾衣架 淘宝 编辑:程序博客网 时间:2024/05/16 10:04
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.
给定两个数组,写一个函数来计算它们的交集。
例如:
给定nums1 = [1, 2, 2, 1],nums2 = [2, 2],返回[2]。
注意:
结果中的每个元素必须是唯一的。
结果可以以任何顺序。
这个题十分的简单,但是我的方法十分的Low
我的时间复杂度达到了平方级别,虽然可以通过,但是Just beat 5.05% 我想没有比我更慢的了。。。
由于前面已经做了一个好像就做数独是否合法的题点击这里查看这个题目,利用了Set集合的特性,那就是重复元素不会被加入到Set集合里面,基于这个,给出我的Bad Ac code。
public static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> res = new HashSet<Integer>(); for (int i = 0; i < nums1.length; i++) { for (int j = 0; j < nums2.length; j++) { if (nums1[i]==nums2[j]) { res.add(nums1[i]); } } } Object[] obj = res.toArray(); int[] resultArray = new int[obj.length]; for (int i = 0; i < obj.length; i++) { resultArray[i] = (int) obj[i];//将Object对象数组转为整型数组(强制向下转型) } return resultArray; }
给出另外的解决方案:
先直接把nums1去重加入set
再遍历nums2 如果set里面有nums2的某元素,则加入另外一个集合
OK
Set<Integer> set = new HashSet<>(); Set<Integer> intersect = new HashSet<>(); for (int i = 0; i < nums1.length; i++) { set.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { if (set.contains(nums2[i])) { intersect.add(nums2[i]); } } int[] result = new int[intersect.size()]; int i = 0; for (Integer num : intersect) { result[i++] = num; } return result;*/
阅读全文
0 0
- leetcode 记录 349. Intersection of Two Arrays
- 349.[Leetcode]Intersection of Two Arrays
- [leetcode] 349. Intersection of Two Arrays
- Leetcode Everyday: 349. Intersection of Two Arrays
- leetcode.349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- Leetcode 349. Intersection of Two Arrays
- leetcode 349. Intersection of Two Arrays
- leetcode 349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- 【leetcode】 349. Intersection of Two Arrays
- Leetcode 349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- Leetcode题解 349. Intersection of Two Arrays
- LeetCode - 349. Intersection of Two Arrays
- [Leetcode]349. Intersection of Two Arrays
- 349. Intersection of Two Arrays--LeetCode Record
- LeetCode 349. Intersection of Two Arrays
- Dalvik虚拟机与Java虚拟机的区别
- 简单计算1+2+3+.......+10 的值
- HDU4738 Caocao's Bridges
- java面向对象的3大特征——封装,继承,多态
- 危险报警
- Leetcode:349. Intersection of Two Arrays
- qtcreator4.4.1远程调试 gdbserver7.8 termcap1.3.1
- vue学习笔记—vue基础(二)
- leetcode(263,389) python实现
- MatConvNet 使用VGG网络模型对图像做分类处理
- 多数相乘之和
- Internet协议
- 信号及信号处理(二): 可靠信号与不可靠信号
- 习题6.3