您的位置:首页 > 其它

LeetCode(2)——Intersection of Two Arrays

2016-07-03 22:07 399 查看
解法一(我自己的)

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()];
//      for(int i=0; i<set.size(); i++) {
//  num[i] = set.get(i);
//      }
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);
}
//      对set2使用迭代器进行遍历,选出set2中包含set1中的元素,即交集
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: