版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014539580/article/details/78147107
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.
java实现HashSet()
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.
要求不能有重复数字,使用set()
python 实现
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
num_set = set()
ret = set()
for x in nums1:
if x not in num_set:
num_set.add(x)
for y in nums2:
if y in num_set and y not in ret:
ret.add(y)
return list(ret)
java实现HashSet()
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer>intersection = new HashSet<Integer>();
HashSet<Integer>set1 = new HashSet<Integer>();
for(int i =0; i<nums1.length; i++){
set1.add(nums1[i]);
}
for(int i =0; i<nums2.length; i++){
if(set1.contains(nums2[i])){
intersection.add(nums2[i]);
}
}
int[]res = new int[intersection.size()];
int i =0;
for(int num: intersection){
res[i] = num;
i++;
}
return res;
}
}
另一种思路空间换时间
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int max = 0;
for(int num: nums1) {
if(num > max) {
max = num;
}
}
for(int num: nums2) {
if(num > max) {
max = num;
}
}
int[] indexMap = new int[max+1];
for(int num: nums1) {
indexMap[num] = 1;
}
int cnt = 0;
for(int num: nums2) {
if(indexMap[num] == 1) {
indexMap[num] = 2;
cnt++;
}
}
int[] result = new int[cnt];
for(int i=0; i<max+1; i++) {
if(indexMap[i] == 2) {
result[--cnt] = i;
}
}
return result;
}
}