Skip to content

Latest commit

 

History

History
123 lines (89 loc) · 2.33 KB

349.Intersection-of-Two-Arrays.md

File metadata and controls

123 lines (89 loc) · 2.33 KB

349. Intersection of Two Arrays


题目地址

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

题目描述

Given two arrays, write a function to compute their intersection.

Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:
Each element in the result must be unique.
The result can be in any order.

代码

Approach #1 Two Sets

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
    	HashSet<Integer> set1 = new HashSet<Integer>();
      for (Integer n: nums1) set1.add(n);
      HashSet<Integer> set2 = new HashSet<Integer>();
      for (Integer n: nums2) set2.add(n);
      
      if (set1.size() < set2.size()) {
        return helper(set1, set2);
      } else {
        return helper(set2, set1);
      }
    }
  
  private int[] helper(HashSet<Integer> set1, (HashSet<Integer> set2) {
    int[] output = new int[set1.size()];
    int idx = 0;
    for (Integer s: set1) {
      if (set2.contains(s)) {
        output[idx++] = s;
      }
    }
    return Arrays.copyOf(output, idx);
  }
}

Approach #2 Built-in Set Intersection

class Solution {
  public int[] intersection(int[] nums1, int[] nums2) {
    HashSet<Integer> set1 = new HashSet<Integer>();
    for (Integer n : nums1) set1.add(n);
    HashSet<Integer> set2 = new HashSet<Integer>();
    for (Integer n : nums2) set2.add(n);

    set1.retainAll(set2);

    int [] output = new int[set1.size()];
    int idx = 0;
    for (int s : set1) output[idx++] = s;
    return output;
  }
}

Approach #3 Two Pointer

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;
    }
}