Intersection of Two Arrays
2016-07-23 04:02
267 查看
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
Note:
Each element in the result must be unique.
The result can be in any order.
Show Tags
Show Similar Problems
解法一:
2 hashset
解法二:
Sort both arrays, use two pointers
Time complexity: O(nlogn)
解法三:
binary search
Time complexity: O(nlogn)
reference:https://discuss.leetcode.com/topic/45685/three-java-solutions
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.
Show Tags
Show Similar Problems
解法一:
2 hashset
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Set<Integer> intersect = new HashSet<>(); for (int i = 0; i < nums1.length; i++) { set.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { if (set.contains(nums2[i])) { intersect.add(nums2[i]); } } int[] result = new int[intersect.size()]; int i = 0; for (Integer num : intersect) { result[i++] = num; } return result; } }
解法二:
Sort both arrays, use two pointers
Time complexity: O(nlogn)
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Arrays.sort(nums1); Arrays.sort(nums2); int i = 0; int j = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] < nums2[j]) { i++; } else if (nums1[i] > nums2[j]) { j++; } else { set.add(nums1[i]); i++; j++; } } int[] result = new int[set.size()]; int k = 0; for (Integer num : set) { result[k++] = num; } return result; } }
解法三:
binary search
Time complexity: O(nlogn)
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Arrays.sort(nums2); for (Integer num : nums1) { if (binarySearch(nums2, num)) { set.add(num); } } int i = 0; int[] result = new int[set.size()]; for (Integer num : set) { result[i++] = num; } return result; } public boolean binarySearch(int[] nums, int target) { int low = 0; int high = nums.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (nums[mid] == target) { return true; } if (nums[mid] > target) { high = mid - 1; } else { low = mid + 1; } } return false; } }
reference:https://discuss.leetcode.com/topic/45685/three-java-solutions
相关文章推荐
- Codeforces Round #364 (Div. 2) 题解
- 面试基础
- 利用jar命令打包和解压
- JavaScript创建对象
- 【C++11】C++11新增的便利算法[1] all_of、any_of 和 none_of
- 暴力枚举,dfs(连连看,HDU 4272)
- DroidPlugin源码分析服务与静态广播的处理
- 算法-巴什博奕
- oracle基于3种方法的大数据量插入更新
- DroidPlugin源码分析处理Activity的启动
- Cards(Codeforces 701A)(Codeforces Round #364Div.2 A)
- entityframework 增删改查
- DroidPlugin源码分析插件进程管理以及预注册Activity,Service,ContentProvide的选择
- Mybatis批量更新数据
- 系统吞吐量、TPS(QPS)、用户并发量、性能测试概念和公式
- cocos2dx实现简单卡牌翻转效果
- 《App研发录》知识点汇总
- 解决编译apache出现的问题:configure: error: APR not found . Please read the documentation
- Spring+MyBatis多数据源配置实现
- Power of Two & Power of Three & Power of Four