350. Intersection of Two Arrays II
来源:互联网 发布:安卓手机php编程 编辑:程序博客网 时间:2024/06/05 21:01
https://leetcode.com/problems/intersection-of-two-arrays-ii/#/description
很简单的问题,求两个集合的交集。写的有点蠢了。。先a了再说
初步思路是,将两个集合各自遍历一遍,映射一下元素,然后将映射后的结果进行对比。
遇到的一个问题是,在取map元素数据的时候,要对map里的数据进行比较,用==不能比较,只能用equals(待解决。。。先吃饭)
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map1 = new HashMap<Integer,Integer>();
for(int i = 0;i < nums1.length;i ++){
if(map1.containsKey(nums1[i])){//已存在
int count = map1.get(nums1[i]);
count ++;
map1.put(nums1[i],count);
}
else{
map1.put(nums1[i],1);
}
}
Map<Integer,Integer> map2 = new HashMap<Integer,Integer>();
for(int i = 0;i < nums2.length;i ++){
if(map2.containsKey(nums2[i])){//已存在
int count = map2.get(nums2[i]);
count ++;
map2.put(nums2[i],count);
}
else{
map2.put(nums2[i],1);
}
}
int lengthMax = Math.max(map1.size(),map2.size());
ArrayList res = new ArrayList();
for (Map.Entry<Integer, Integer> entry1 : map1.entrySet()) {
for (Map.Entry<Integer, Integer> entry2 : map2.entrySet()) {
/* int a = entry1.getKey();
int b = entry2.getKey();
if(a == b){*/
if(entry1.getKey().equals(entry2.getKey())){
int lengthMin = Math.min(entry1.getValue(),entry2.getValue());
for(int i = 0;i < lengthMin;i ++){
res.add(entry1.getKey());
}
}
}
}
int size=res.size();
int [] resInt = new int[size];
for(int i = 0;i < size;i ++){
resInt[i] = (int)res.get(i);
}
return resInt;
}
}
- 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II【E】
- 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- (转)Android:控件AutoCompleteTextView 自动提示
- 设计模式
- 继续坑自己,EmguCV之SVM.Train(二)
- iOS支付宝开发流程与常见的问题
- Android Studio 使用CMake实现自己的.so库
- 350. Intersection of Two Arrays II
- C#访问远程主机资源的方法,多种方式
- 题目1200:最大的两个数
- Unity3D引擎之渲染技术系列四
- 关于阻止冒泡的兼容性写法以及判断目标点的兼容性写法
- 静态、抽象类、接口
- 【HDU3401】Trade-单调队列优化DP
- 深度剖析ConcurrentHashMap
- 括号匹配算法的一种正确实现(java)