leetcode [#349]

目录

题目

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.

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
HashSet<Integer> set = new HashSet<Integer>();
int a = nums1.length;
int b = nums2.length;
int i=0,j=0;
while(i<a && j<b){
if(nums1[i] == nums2[j]){
set.add(nums1[i]);
i++;
j++;
} else if(nums1[i] < nums2[j]){
i++;
} else {
j++;
}
}
int[] sect = new int[set.size()];
Iterator ir = set.iterator();
for(int k = 0; ir.hasNext(); k++){
sect[k] = (int) ir.next();
}
return sect;
}
}

注意事项

  1. 使用Java的HashSet,HashSet是通过HashMap实现的,是存在于java.util包中的类。该容器中只能存储不重复的对象。不能通过get()方法获取元素,可通过实现Iterable接口迭代获取所有元素。
  2. 将两个数组排序后,通过一遍对两个数组的比较,就可以获取所有相同的元素(并且重复的只存储了一次)。这种方法的复杂度是由Arrays.sort()方法决定的,该方法的实现采用三向快速排序或者归并排序,保证了复杂度在o(nlogn),相比于通过两层for循环嵌套进行暴力筛选要好很多。