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.

解答

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
28
29
30
31
32
33
34
35
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length==0||nums2.length==0){
int[] fuck = new int[0];
return fuck;
}
ArrayList<Integer>Temp = new ArrayList<Integer>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = -1;
int temp = nums2[0]-1;
do{
i++;
for(int j = 0;j<nums1.length;j++){
if(nums2[i] == nums1[j]){
if(temp == nums2[i]){
continue;
}
temp = nums2[i];
Temp.add(temp);
break;
}
if(nums1[j]>nums2[i]){
break;
}
}
}while(i<nums2.length-1);
int l = Temp.size();
int[] res = new int[l];
for(int k =0;k<l;k++){
res[k] = Temp.get(k);
}
return res;
}
}