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.

要求不能有重复数字,使用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) {
        HashSetintersection = new  HashSet();
        HashSetset1 = new HashSet();
        for(int i =0; i
另一种思路空间换时间

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



你可能感兴趣的:(LeetCode)