leetcode_350 Intersection of Two Arrays II
来源:互联网 发布:ubuntu google输入法 编辑:程序博客网 时间:2024/05/24 00:52
题目分析:
给定两个数组,求数组的交集。输出结果中的元素不唯一,输出数组可以无序。
解题思路:
1)对数组nums1进行排序;
2)对数组nums2进行排序;
3)遍历数组nums1和nums2中元素,并比较对应的元素,
- 若相等,则将其保存到输出结果中,并变化两个数组对应的索引
- 不等,则变化较小元素对应的索引即可。
实现程序
C++版本
vector<int> intersect(vector<int> &nums1, vector<int> &nums2){ // 对数组1进行排序 sort(nums1.begin(), nums1.end()); // 对数组2进行排序 sort(nums2.begin(), nums2.end()); vector<int> result; for (int i = 0, j = 0; i < nums1.size() && j < nums2.size(); ) { if (nums1[i] == nums2[j]) { result.push_back(nums1[i]); i++; j++; } else if (nums1[i] < nums2[j]) i++; else if (nums1[i] > nums2[j]) j++; } return result;}
Java版本
public int[] intersect(int[] nums1, int[] nums2){ Arrays.sort(nums1); Arrays.sort(nums2); ArrayList result = new ArrayList(); for (int i = 0, j = 0; i < nums1.length && j < nums2.length; ){ if (nums1[i] == nums2[j]){ result.add(nums1[i]); i++; j++; } else if (nums1[i] < nums2[j]) { i++; } else { j++; } } int[] res = new int[result.size()]; for (int i = 0; i < result.size(); i++){ res[i] = (int) result.get(i); } return res;}
0 0
- leetcode_350 Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays&Intersection of Two Arrays II
- [LeetCode] Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 51 nod 1396 还是01串
- Python2.x和Python3.x的区别
- Android22之Pull解析xml
- java设计模式-外观模式
- NeuralTalk2---自动产生图片的语句描述
- leetcode_350 Intersection of Two Arrays II
- bootstrap中的dropdown组件改造click为hover
- Qt没有被正确安装
- php.ini 常用的配置
- http请求学习
- Javascript的Date类型总结
- Spark--用Java开发微服务
- 51 nod 数组的最大代价
- MapReduce计数器