349. Intersection of Two Arrays

Easy

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.
package leetcode.easy;

public class IntersectionOfTwoArrays {
	public int[] set_intersection(java.util.HashSet<Integer> set1, java.util.HashSet<Integer> set2) {
		int[] output = new int[set1.size()];
		int idx = 0;
		for (Integer s : set1) {
			if (set2.contains(s)) {
				output[idx++] = s;
			}
		}

		return java.util.Arrays.copyOf(output, idx);
	}

	public int[] intersection1(int[] nums1, int[] nums2) {
		java.util.HashSet<Integer> set1 = new java.util.HashSet<Integer>();
		for (Integer n : nums1) {
			set1.add(n);
		}
		java.util.HashSet<Integer> set2 = new java.util.HashSet<Integer>();
		for (Integer n : nums2) {
			set2.add(n);
		}

		if (set1.size() < set2.size()) {
			return set_intersection(set1, set2);
		} else {
			return set_intersection(set2, set1);
		}
	}

	public int[] intersection2(int[] nums1, int[] nums2) {
		java.util.HashSet<Integer> set1 = new java.util.HashSet<Integer>();
		for (Integer n : nums1) {
			set1.add(n);
		}
		java.util.HashSet<Integer> set2 = new java.util.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;
	}

	@org.junit.Test
	public void test1() {
		int[] nums1 = { 1, 2, 2, 1 };
		int[] nums2 = { 2, 2 };
		int[] result = intersection1(nums1, nums2);
		for (int i = 0; i < result.length; i++) {
			System.out.print(result[i] + " ");
		}
		System.out.println();
		result = intersection2(nums1, nums2);
		for (int i = 0; i < result.length; i++) {
			System.out.print(result[i] + " ");
		}
		System.out.println();
	}

	@org.junit.Test
	public void test2() {
		int[] nums1 = { 4, 9, 5 };
		int[] nums2 = { 9, 4, 9, 8, 4 };
		int[] result = intersection1(nums1, nums2);
		for (int i = 0; i < result.length; i++) {
			System.out.print(result[i] + " ");
		}
		System.out.println();
		result = intersection2(nums1, nums2);
		for (int i = 0; i < result.length; i++) {
			System.out.print(result[i] + " ");
		}
		System.out.println();
	}
}
01-18 18:45