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.
题目:一目了然找出两个数组的交集
思路:我的大概想法是,先将两个数组分别去重,而后合成一个数组,对该数组进行排序,而后数组中相邻两个元素相等的即为交集元素,即num[i] == num[i-1]
代码有点冗余,效率一般,
public int[] intersection(int[] nums1, int[] nums2) {
int len1 = nums1.length, len2 = nums2.length, j = 0;
if(len1 == 0 || len2 == 0){ return new int[0]; } HashSet<Integer> set1 = new HashSet<Integer>(); HashSet<Integer> set2 = new HashSet<Integer>(); HashSet<Integer> set3 = new HashSet<Integer>(); for (int i = 0; i < len1; i++) { set1.add(nums1[i]); } for (int i = 0; i < len2; i++) { set2.add(nums2[i]); } int[] temp = new int[set1.size() + set2.size()]; Iterator it1 = set1.iterator(); while (it1.hasNext()) { temp[j++] = (Integer) it1.next(); } Iterator it2 = set2.iterator(); while (it2.hasNext()) { temp[j++] = (Integer) it2.next(); } Arrays.sort(temp);for (int i = 1; i < temp.length; i++) {
if (temp[i] == temp[i - 1] ) { set3.add(temp[i]); } } int res[] = new int[set3.size()]; j = 0; Iterator it3 = set3.iterator(); while (it3.hasNext()) { res[j++] = (Integer) it3.next(); } return res; }