Intersection of Two Arrays(交集)

来源:https://leetcode.com/problems/intersection-of-two-arrays

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.

1. 直接使用HashSet

 1 class Solution {
 2     public int[] intersection(int[] nums1, int[] nums2) {
 3         Set<Integer> set = new HashSet<>();
 4         Set<Integer> intersect = new HashSet<>();
 5         for(int i=0; i<nums1.length; i++) {
 6             set.add(nums1[i]);
 7         }
 8         for(int i=0; i<nums2.length; i++) {
 9             if(set.contains(nums2[i])) {
10                 intersect.add(nums2[i]);
11             }
12         }
13         int[] result = new int[intersect.size()];
14         int i = 0;
15         for(Integer num: intersect) {
16             result[i++] = num;
17         }
18         return result;
19     }
20 }// 6 ms

2. 类似BitMap的思想,LeetCode 1ms sample,缺点是数组中的元素不能为负数……

(1)求出两个数组的最大值

(2)建立 长度=最大值+1 的数组A,假设数组的索引为i,那么A[i]的值表示i是否在两个数组中存在,若为0表示不存在于任何一个数组中,为1表示存在于第一个数组中,为2表示两个数组中都存在

 1 class Solution {
 2     public int[] intersection(int[] nums1, int[] nums2) {
 3         int max = 0;
 4         for(int num: nums1) {
 5             if(num > max) {
 6                 max = num;
 7             }
 8         }
 9         for(int num: nums2) {
10             if(num > max) {
11                 max = num;
12             }
13         }
14         int[] indexMap = new int[max+1];
15         for(int num: nums1) {
16             indexMap[num] = 1;
17         }
18         int cnt = 0;
19         for(int num: nums2) {
20             if(indexMap[num] == 1) {
21                 indexMap[num] = 2;
22                 cnt++;
23             }
24         }
25         int[] result = new int[cnt];
26         for(int i=0; i<max+1; i++) {
27             if(indexMap[i] == 2) {
28                 result[--cnt] = i;
29             }
30         }
31         return result;
32     }
33 }
原文地址:https://www.cnblogs.com/renzongxian/p/7545365.html