LeetCode 349 Intersection of Two Arrays [sort] java

Source address: 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.

方法很简单,用一个hashmap来保存第一个数组出现了那些数字。然后如果一个数字在第二个数组同时也在第一个数组,那么就加入到第二个hashmap。然后把第二个hashmap的全部元素输出。

We use one hashmap to store which number appears in the first array. And if any number in the second array is also in the hashmap 1. We put it to hashmap 2. In the end, we output every element in hashmap 2.

Github address: https://github.com/tinyfool/leetcode/tree/master/src/p0349

To find other sort problems, see also Sort algorithms and problems.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.