Leetcode349. Intersection of Two Arrays
来源:互联网 发布:淘宝怎么才能没有同款 编辑:程序博客网 时间:2024/05/17 09:03
题目描述:
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中,然后将第二个数组中的元素分别依次比较,看是否在HashSet中,如果存在则添加到需要返回的结果数组中。
最终实现:
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null) { return null; } Set<Integer> set1 = new HashSet<>(); for (int i:nums1) { set1.add(i); } Set<Integer> set2 = new HashSet<>(); for (int i:nums2) { if (set1.contains(i)) { set2.add(i); } } int[] result = new int[set2.size()]; int i = 0; for (int n:set2) { result[i++] = n; } return result; } }
这种方法时间复杂度为O(n),空间复杂度为O(n)。
另外的解:
- 另外一种解题思路是,首先对数组进行排列,然后借助Arrays中的binarySearch方法,对每个元素进行二分查找,具体实现如下:
public class Solution { public static int[] intersection(int[] num1, int[] num2) { Arrays.sort(num1); Arrays.sort(num2); ArrayList<Integer> aList = new ArrayList<>(); for (int i = 0; i < num1.length; i++) { if (i == 0 || (i > 0 && num1[i] != num1[i-1])) { if (Arrays.binarySearch(num2, num1[i]) > -1) { aList.add(num1[i]); } } } int[] result = new int[aList.size()]; int k = 0; for (int i : aList) { result[k++] = i; } return result; } }
对于上面的binarySearch方法,即可以自己实现也可以调用Arrays类中的静态方法,在这里就不实现了。
0 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
- Asynctask + HttpClient 和Volley框架
- mysql 关联查询 索引不起作用原因记录
- 从头到尾解析Hash表算法
- 2016保研综述
- NOIP游记TAT
- Leetcode349. Intersection of Two Arrays
- kruskal算法-最小生成树
- Swift-重写与重载的使用和比较
- 《outliers》/《异类》读后有所思
- POJ-2342-Anniversary party(树形DP)
- NSGA-II 非支配排序算法
- 项目可行性的研究内容
- Prime Ring Problem
- Spring点点滴滴之静态代理