349. Intersection of Two Arrays
来源:互联网 发布:hyper v配置nat网络 编辑:程序博客网 时间:2024/06/07 06:08
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 class Solution { public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer> nums1hs = new HashSet<Integer>(); HashSet<Integer> nums2hs = new HashSet<Integer>(); for (int i = 0; i < nums1.length; i++) { nums1hs.add(nums1[i]); } for (int j = 0; j < nums2.length; j++) { if (nums1hs.contains(nums2[j])) { nums2hs.add(nums2[j]); } } int[] result = new int[nums2hs.size()]; int index = 0; for( Integer num : nums2hs ) { result[index++] = num; } return result; }}还有另外两种解法,用sort 和binary search 的思想:
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; }}
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
- android:Retrofit+LoganSquare的简单用法
- exercise 12 提示
- text-size-adjust
- exercsie13 参数 解包 变量
- 2017年开始的旅程
- 349. Intersection of Two Arrays
- CentOS6重启后DNS被还原的解决办法
- 多线程(多线程面试题)
- LeetCode 150. Evaluate Reverse Polish Notation
- Android 应用资源(二) drawable state
- Android 应用资源(三) Shape Drawable使用详解
- Walls and Gates
- Android 动画篇—alpha、scale、translate、rotate、set的xml属性及用法
- Android 6.0 运行时在Fragment中申请权限无法回调 问题