LeetCode - Easy - 350. Intersection of Two Arrays II

Topic

  • Hash Table
  • Two Pointers
  • Binary Search
  • Sort

Description

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

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

Example 1:

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

Example 2:

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

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Analysis

方法一:我寫的。

方法二:別人寫的,與方法一思路一致,代碼簡潔些。

方法三:排序兩數組,然後用兩指針齊齊比較得出結果。

方法四:Java8式寫法。

Submission

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class IntersectionOfTwoArraysII {

	// 方法一:我寫的
	public int[] intersect1(int[] nums1, int[] nums2) {
		if (nums1 == null || nums2 == null || //
				nums1.length == 0 || nums2.length == 0)
			return new int[] {};

		if (nums1.length > nums2.length) {// 這if語塊可省略
			int[] temp = nums1;
			nums1 = nums2;
			nums2 = temp;
		}

		Map<Integer, Integer> num2count = new HashMap<>();

		for (int n : nums1) {
			Integer count = num2count.get(n);
			if (count == null)
				count = 0;
			num2count.put(n, count + 1);
		}

		List<Integer> list = new ArrayList<>();
		for (int n : nums2) {
			Integer count = num2count.get(n);
			if (count != null && count > 0) {
				list.add(n);
				num2count.put(n, count - 1);
			}
		}
		int[] result = new int[list.size()];

		for (int i = 0; i < list.size(); i++)
			result[i] = list.get(i);

		return result;
	}

	// 方法二:別人寫的,與方法一思路一致,代碼簡潔些
	public int[] intersect2(int[] nums1, int[] nums2) {
		HashMap<Integer, Integer> map = new HashMap<>();
		for (int i : nums1)
			map.put(i, map.getOrDefault(i, 0) + 1);

		ArrayList<Integer> list = new ArrayList<>();
		for (int i : nums2) {
			if (map.get(i) != null && map.get(i) > 0) {
				list.add(i);
				map.put(i, map.get(i) - 1);
			}
		}
		int[] ret = new int[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ret[i] = list.get(i);
		}
		return ret;
	}

	// 方法三:排序兩數組,然後齊齊
	public int[] intersect3(int[] nums1, int[] nums2) {
		Arrays.sort(nums1);
		Arrays.sort(nums2);
		int n = nums1.length, m = nums2.length;
		int i = 0, j = 0;
		List<Integer> list = new ArrayList<>();
		while (i < n && j < m) {
			int a = nums1[i], b = nums2[j];
			if (a == b) {
				list.add(a);
				i++;
				j++;
			} else if (a < b) {
				i++;
			} else {
				j++;
			}
		}
		int[] ret = new int[list.size()];
		for (int k = 0; k < list.size(); k++)
			ret[k] = list.get(k);
		return ret;
	}

	// 方法四:Java8版
	public int[] intersect4(int[] nums1, int[] nums2) {
		Map<Integer, Long> map = Arrays.stream(nums2).boxed()
				.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
		return Arrays.stream(nums1).filter(e -> {
			if (!map.containsKey(e))
				return false;
			map.put(e, map.get(e) - 1);
			if (map.get(e) == 0)
				map.remove(e);
			return true;
		}).toArray();
	}

}

Test

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

public class IntersectionOfTwoArraysIITest {

	@Test
	public void test1() {
		IntersectionOfTwoArraysII obj = new IntersectionOfTwoArraysII();

		int[] array1 = { 1, 2, 2, 1 };
		int[] array2 = { 2, 2 };

		assertArrayEquals(array2, obj.intersect1(array1, array2));
		assertArrayEquals(array2, obj.intersect2(array1, array2));
		assertArrayEquals(array2, obj.intersect3(array1, array2));
		assertArrayEquals(array2, obj.intersect4(array1, array2));
	}

	@Test
	public void test2() {
		IntersectionOfTwoArraysII obj = new IntersectionOfTwoArraysII();

		int[] array1 = { 4, 9, 5 };
		int[] array2 = { 9, 4, 9, 8, 4 };
		int[] expected = { 9, 4 }, actual;
		Arrays.sort(expected);

		actual = obj.intersect1(array1, array2);
		Arrays.sort(actual);
		assertArrayEquals(expected, actual);

		actual = obj.intersect2(array1, array2);
		Arrays.sort(actual);
		assertArrayEquals(expected, actual);

		actual = obj.intersect3(array1, array2);
		Arrays.sort(actual);
		assertArrayEquals(expected, actual);

		actual = obj.intersect4(array1, array2);
		Arrays.sort(actual);
		assertArrayEquals(expected, actual);

	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章