349. Intersection of Two Arrays
来源:互联网 发布:怎么看淘宝店家链接 编辑:程序博客网 时间:2024/06/07 18:58
//本文内容来自StarSight,欢迎访问。
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
public int[] intersection(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); Arrays.sort(nums1); Arrays.sort(nums2); for (int i = 0; i < nums1.length; i++) { binarySearch(nums2, nums1[i], 0, nums2.length - 1, map); } Set keys = map.keySet(); int[] key = new int[keys.size()]; Iterator it = keys.iterator(); for (int i = 0; i < keys.size(); i++) { key[i] = (int)it.next(); } return key; } public void binarySearch(int[] nums, int findNum, int start, int end, Map<Integer, Integer> map) { if (start < end) { int middle = (end - start) / 2 + start; if (nums[middle] > findNum) { binarySearch(nums, findNum, start, middle - 1, map); } else if (nums[middle] < findNum) { binarySearch(nums, findNum, middle + 1, end, map); } else { map.put(findNum, middle); } } else if (start == end) { if (nums[start] == findNum) { map.put(findNum, start); } } }
要用二叉搜索先排序。
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
- springMvc 前端用json的方式向后台传递对象数组
- ACM:蓝桥杯:Fibonacci数列
- 面试中的排序算法总结
- (15.1.23)Guitar-Structure
- SpringMvc运行原理
- 349. Intersection of Two Arrays
- HandlerThread详解
- Java多态
- 58. Length of Last Word
- AS Error:Failed to resolve: javax.inject:javax.inject:1问题解决
- android 无预加载的viewpager
- [机器学习篇]基于Scikit learn库中KNN,SVM算法的笔迹识别
- Ubuntu下 sqlitebrowser 查看 Android Sqlite数据库
- UML常用图的几种关系的总结