Leetcode brush Title java 349. intersection of two arrays

Implementation results:

adopt

Display details

Execution time: 8 ms, beating 66.35% of all Java submissions

Memory consumption: 37.6 MB, beating 29.53% of all Java submissions

Title:

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]
Explain:

Each element in the output must be unique.
We can ignore the order of output.

Train of thought:

Using two hashset s, one for creating a dictionary-like function and one for storing results, while taking advantage of the non-repeatability of set

In fact, the way of thinking is relatively simple. The key point is whether the knowledge point is familiar, and whether we can skillfully use the method of aggregation, such as iterator or something.

Code:

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        //Used to create a hashset dictionary
        Set<Integer> set=new HashSet<>();
        //Used to record results, but also to take advantage of the set's non-repeatability
        Set<Integer> set1=new HashSet<>();
        //Choose a small one to create a dictionary
        if(nums1.length>=nums2.length)
        {
            for(int x:nums2)
            {
                set.add(x);
            }
            for(int y:nums1)
            {
                if(set.contains(y))
                {
                    set1.add(y);
                }
            }
        }else
        {
            for(int x:nums1)
            {
                set.add(x);
            }
            for(int y:nums2)
            {
                if(set.contains(y))
                {
                    set1.add(y);
                }
            }
        }
        //Using iterators to extract content from a collection
        Iterator<Integer> it=set1.iterator();
        int[] result=new int[set1.size()];
        int index=0;
        while(it.hasNext())
        {
            result[index++]=it.next();
        }
        return result;
    }
}

 

Keywords: Java

Added by Rhysyngsun on Fri, 04 Oct 2019 11:52:13 +0300