leetcode349. Intersection of Two Arrays
来源:互联网 发布:汽车销售软件有哪些 编辑:程序博客网 时间:2024/06/05 02:53
349. Intersection of Two Arrays
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.
解法一
先排序,然后用hashset存储相同的元素,然后遍历set,存到数组中。
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1 == null || nums1.length == 0) { return nums1; } if (nums2 == null || nums2.length == 0) { return nums2; } Set<Integer> set = new HashSet<Integer>(); Arrays.sort(nums1); Arrays.sort(nums2); int i = 0, j = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] < nums2[j]) { i++; } else if (nums1[i] == nums2[j]) { set.add(nums1[i]); i++; j++; } else { j++; } } int size = set.size(); int[] ret = new int[size]; int k = 0; for (int num : set) { ret[k++] = num; } return ret; }}
解法二
用两个hashset,第一个hashset存储第一个数组中的不重复元素,第二个hashset存储两个数组的重复元素。遍历hashset用的iterator方法。
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1 == null || nums1.length == 0) { return nums1; } if (nums2 == null || nums2.length == 0) { return nums2; } Set<Integer> set1 = new HashSet<Integer>(); Set<Integer> set2 = new HashSet<Integer>(); for (int i = 0; i < nums1.length; i++) { set1.add(nums1[i]); } for (int j = 0; j < nums2.length; j++) { if (set1.contains(nums2[j])) { set2.add(nums2[j]); } } int size = set2.size(); int[] ret = new int[size]; int k = 0; Iterator<Integer> it = set2.iterator(); while (it.hasNext()) { ret[k++] = it.next(); } return ret; }}
1 0
- leetcode349: Intersection of Two Arrays
- Leetcode349. Intersection of Two Arrays
- Leetcode349. Intersection of Two Arrays
- Leetcode349. Intersection of Two Arrays
- LeetCode349. Intersection of Two Arrays
- LeetCode349 Intersection of Two Arrays
- leetcode349~Intersection of Two Arrays
- leetcode349. Intersection of Two Arrays
- leetcode349. Intersection of Two Arrays
- Leetcode349 - Intersection of Two Arrays(two pointers)
- LeetCode349. Intersection of Two Arrays我的做法
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Linux软件开发工程师
- 表达式求值
- 蓝桥杯--DP-完全背包
- JMeter 中_time 函数的使用(时间戳、当前时间)
- C++之模板
- leetcode349. Intersection of Two Arrays
- 代码注释:机器学习实战第8章 预测数值型数据:回归
- 500Illegal_PORT_command的问题_主被动模式
- 2017去哪网春招编程题详解
- C语言陷阱学习总结
- NOIP2011 选择客栈
- Range Sum Query
- 手机键盘
- struts2.5方法访问篇