349. Intersection of Two Arrays
来源:互联网 发布:网络效应和锁定效应 编辑:程序博客网 时间:2024/06/06 00:35
问题描述:给你两个数组,找出它们的公共数字。
思路:通过map对已有数字进行存储读取。
原答案:
public int[] intersection(int[] nums1, int[] nums2) { int length=nums1.length; Map<Integer,Boolean> map=new HashMap<Integer,Boolean>(); Map<Integer,Boolean> resMap=new HashMap<Integer,Boolean>(); List<Integer> list=new ArrayList<Integer>(); for(int i=0;i<length;i++){ map.put(nums1[i],true); } length=nums2.length; for(int j=0;j<length;j++){ if(map.containsKey(nums2[j])&&(!resMap.containsKey(nums2[j]))){ resMap.put(nums2[j],true); list.add(nums2[j]); } } int size=list.size(); int[] res=new int[size]; for(int k=0;k<size;k++){ res[k]=list.get(k); } return res; }
最佳答案:
public int[] intersection(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return new int[0]; List<Integer> res = new ArrayList<>(); int max = nums1[0], min = nums1[0]; for (int i = 1; i < nums1.length; i++){ if (nums1[i] > max) max = nums1[i]; else if (nums1[i] < min) min = nums1[i]; } boolean[] bucket = new boolean[max - min + 1]; for (int num: nums1) bucket[num - min] = true; for (int num: nums2){ if (num >= min && num <= max){ if (bucket[num - min]){ res.add(num); bucket[num - min] = false; } } } int[] result = new int[res.size()]; for (int i = 0; i < res.size(); i++){ result[i] = res.get(i); } return result; }
差距分析:其实不需要用map进行存储。用数组就可以存储了。最佳答案中存储方法是找出数组的最大值最小值,从而确定数组的最大范围。然后通过数值计算实现去重,并实现取数。
阅读全文
0 0
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays[][
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- View的getWidth()和getMeasuredWidth()有什么区别吗?如何在onCreate中拿到View的宽度和高度?
- dos操作
- 【转】对Finger-vein biometric identification using convolutional neural network的理解以及扩展应用
- 人为什么会走向平庸?
- 数据结构第五周项目-自建算法库链栈
- 349. Intersection of Two Arrays
- 算法-排序-快速排序
- XTU1177 Grid--组合数
- 看看什么时候被收录
- Spark核心RDD:foldByKey函数详解
- [leetcode] 26. Remove Duplicates from Sorted Array
- 每天一道LeetCode-----将数字集转成字母集,计算有多少种转换方式
- DOM、javaScript与HTML
- HDU P2089 不要62