leetcode [#350]

目录

题目

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • 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
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> list = new ArrayList<Integer>();
int a = nums1.length;
int b = nums2.length;
int i=0,j=0;
while(i<a && j<b){
if(nums1[i] == nums2[j]){
list.add(nums1[i]);
i++;
j++;
} else if(nums1[i] < nums2[j]){
i++;
} else {
j++;
}
}
int[] sect = new int[list.size()];
for(int k = 0;k < list.size(); k++){
sect[k] = list.get(k);
}
return sect;
}
}

注意事项

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