349. Intersection of Two Arrays
- Total Accepted: 52852
- Total Submissions: 118189
- Difficulty: Easy
- Contributors: Admin
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.
给你两个数组,求两个数组中重复的元素
一直在用C++写ACM题,对java类库不是很熟悉,知道应该用set写,但是不会用hashset。。。。于是纯暴力写了一个,不过时间复杂度还好,A了之后学了一下set用法,一起放到这里
暴力解法:
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int hash1[] = new int [65535];
int hash2[] = new int [65535];
for(int i=0;i<len1;i++){
hash1[nums1[i]]++;
}
for(int i=0;i<len2;i++){
hash2[nums2[i]]++;
}
int index = 0;
int count = 0;
for(int i=0;i<len1;i++){
if(hash2[nums1[i]] == 0){
hash1[nums1[i]] = 0;
}
}
for(int i=0;i<65535;i++){
if(hash1[i] != 0){
count++;
}
}
int re[] = new int [count];
for(int i=0;i<65535;i++){
if(hash1[i] != 0){
re[index++] = i;
}
}
return re;
}
}
HashSet:
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer>set = new HashSet<Integer>();
int len1 = nums1.length;
int len2 = nums2.length;
for(int i=0;i<len1;i++){
set.add(nums1[i]);
}
List<Integer>list = new ArrayList<Integer>();
for(int i=0;i<len2;i++){
if(set.contains(nums2[i])){
list.add(nums2[i]);
set.remove(nums2[i]);
}
}
int size = list.size();
int re[] = new int [size];
for(int i=0;i<size;i++){
re[i] = list.get(i);
}
return re;
}
}