p349

LeetCode P349 Intersection of Two Arrays 题解

1.题目:

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.

题意:

输入两个int类型的数组,返回一个数组内容是它们的公共部分,不允许有重复,顺序随意

2.解题思路:
先将第一个数组存入set1中(查看set的介绍),这样就先除去了第一个数组中重复的元素,
再遍历第二个数组,如果其中元素被set1包涵则添加set2中,这样又除去了答案中重复的元素。最后转换输出。

3.代码


[title] [] [url] [link text]
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
 
package leetcode;

import java.awt.List;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
*
* @author ZhangMengRou
*
*/
public class p349 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();
String b = in.nextLine();

int[] nn1 = new int[(a.length() + 1) / 2];
String[] n1 = a.split(" ");

for (int i = 0; i < (a.length() + 1) / 2; i++) {
nn1[i] = Integer.parseInt(n1[i]);
// System.out.println(nn1[i]);
}
int[] nn2 = new int[(b.length() + 1) / 2];
String[] n2 = b.split(" ");
for (int i = 0; i < (b.length() + 1) / 2; i++) {
nn2[i] = Integer.parseInt(n2[i]);
// System.out.println(nn2[i]);
}

//完成数据的输入并进行处理
int[] ans = intersection(nn1, nn2);
for (int i = 0; i < ans.length; i++) {
System.out.println(ans[i]);
}

}

public static int[] intersection(int[] nums1, int[] nums2) {
int a = nums1.length;
int b = nums2.length;



int j = 0;
Set<Integer> set = new HashSet<>();
Set<Integer> setans = new HashSet<>();
for (int i = 0; i < a; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < b; i++) {
if (set.contains(nums2[i])) {
setans.add(nums2[i]);

}

}
//注意确定生成的数组的大小
j = setans.size();
int[] ans = new int[j];
for (Integer i : setans) {
ans[j - 1] = (int) i;
j--;

}

return ans;

}
}



4.一些总结:总结下踩过的坑。。不了解set..&&一开始跟C语言一样的想法把数组往大了开。。结果Wrong了。。多出来的输出了0。。
基础要补orz
ps:感谢ljx提示快捷键syso输出