LeetCode(2)——Intersection of Two Arrays
2016-07-03 22:07
399 查看
解法一(我自己的)
解法二(参考LeetCode上的答案)
注意:迭代器要注意设置迭代器的类型,否则默认为是Object类型,导致编译不通过
自己在对迭代器那块可能有点不是很熟悉,所以需要多多练习
解法三(参考LeetCode上的答案):
值得学习的地方:对Arrays的使用
这里的那个if语句需要好好琢磨怎么写
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; } }
相关文章推荐
- 怎么将excel中的小数变成整数(不只是隐藏小数部分哦)?
- grunt 记录
- 7.4 私有变量
- C语言 求两个数的最大公约数
- laravel框架学习(一)
- easyui radio 无法选中的原因
- 'XCTest/XCTest.h' file not found
- 新手应该如何入门前端
- 算法_归并排序
- 【Java进阶四】抽象类和接口
- C语言 将三个数按从大到小输出
- http session
- ubuntu dpkg -i 依赖问题
- android的生命周期
- 组合测试法中的全对偶测试法
- Shiro 安全框架
- 农夫过河
- 数据结构之Dijkstra算法
- 【NOIP12TGD2T2】洛谷1083 借教室
- C语言 将一个整数的二进制序列分别输出