- 解法一(我自己的)
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<Integer>();
for(int i=0; i<nums1.length; i++) {
for(int j=0; j<nums2.length; j++) {
if(nums1[i] == nums2[j]) {
set.add(nums1[i]);
}
}
}
int[] num = new int[set.size()];
int m = 0;
for(int i:set)
num[m++] = i;
return num;
}
}
- 解法二(参考LeetCode上的答案)
注意:迭代器要注意设置迭代器的类型,否则默认为是Object类型,导致编译不通过
自己在对迭代器那块可能有点不是很熟悉,所以需要多多练习
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
for(int i:nums1) {
set1.add(i);
}
Set<Integer> set2 = new HashSet<Integer>();
for(int i:nums2) {
set2.add(i);
}
Iterator<Integer> it = set1.iterator();
while(it.hasNext()) {
int i = it.next();
if(!set2.contains(i)) {
it.remove();
}
}
int[] result = new int[set1.size()];
int i=0;
for(int x :set1) {
result[i++] = x;
}
return result;
}
}
- 解法三(参考LeetCode上的答案):
值得学习的地方:对Arrays的使用
这里的那个if语句需要好好琢磨怎么写
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<nums1.length; i++) {
if(i==0 || (i>0 && nums1[i] != nums1[i-1])) {
if(Arrays.binarySearch(nums2, nums1[i])>-1) {
list.add(nums1[i]);
}
}
}
int[] result = new int[list.size()];
int k=0;
for(int x:list) {
result[k++] = x;
}
return result;
}
}