leetcode解题之349 & 350. Intersection of Two Arrays Java版(求数组交集))

349. 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.

求两个数组的交集,元素不能重复。

使用map

import java.util.*;

public class Solution {
	public int[] intersection(int[] nums1, int[] nums2) {
		List list = new ArrayList<>();
		Map map = new HashMap<>();
		//把nums1放入map中,map中的value值多少无所谓
		for (int i = 0; i < nums1.length; i++)
			map.put(nums1[i], map.get(nums1[i]) == null
			? 1 : map.get(nums1[i]) + 1);
		for (int i = 0; i < nums2.length; i++)
			//如果map中含有nums2[i],并且list中没有则存入
			if (map.containsKey(nums2[i]) && !list.contains(nums2[i])) {
				list.add(nums2[i]);
			}
		int num[] = new int[list.size()];
		int i = 0;
		for (Integer integer : list) {
			num[i++] = integer;
		}
		return num;
	}
}

350. Intersection of Two Arrays II

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

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return[2, 2].

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 tonums2'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?

求两个数组的交集,元素有重复。

【思路】用两个map分别存储两个数组中的元素,将相同元素,次数较少的存入结果中。

import java.util.*;
//使用哈希表存储
public class Solution {
	public int[] intersect(int[] nums1, int[] nums2) {
		Map map1 = new HashMap<>();
		Map map2 = new HashMap<>();
		List res = new ArrayList<>();
		// 把nums1元素和出现的次数存入到map1中
		for (int i = 0; i < nums1.length; i++)
			map1.put(nums1[i], map1.get(nums1[i]) == null ? 1 : map1.get(nums1[i]) + 1);
		// 把nums2元素和出现的次数存入到map2中
		for (int i = 0; i < nums2.length; i++)
			map2.put(nums2[i], map2.get(nums2[i]) == null ? 1 : map2.get(nums2[i]) + 1);
		for (int i = 0; i < nums1.length; i++) {
			// 如果map2中的key包含map1中的key(有交集),并且格子的value没有减少到0
			if (map2.containsKey(nums1[i]) && map1.get(nums1[i]) != 0 && map2.get(nums1[i]) != 0) {
				// 结果加入到res中,并且key的数量减少
				res.add(nums1[i]);
				map1.put(nums1[i], map1.get(nums1[i]) - 1);
				map2.put(nums1[i], map2.get(nums1[i]) - 1);
			}
		}
		int num[] = new int[res.size()];
		int i = 0;
		for (Integer integer : res) {
			num[i++] = integer;
		}
		return num;
	}

你可能感兴趣的:(leetcode)