How to find the intersection of two arrays in LeetCode
This article is about how to find the intersection of two arrays in LeetCode. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.
1. Brief introduction of the problem.
Given two arrays, write a function to calculate their intersection.
2, example
Example 1:
Input: nums1 = [1Pert 2je 2je 1], nums2 = [2je 2] output: [2] example 2:
Input: nums1 = [4jin9pr 5], nums2 = [9je 4je 9je 8je 4] output: [9je 4]
Description:
Each element in the output must be unique. We can ignore the order of the output results.
3, the train of thought of solving the problem
The use of hashSet and collection methods
4, problem solving procedure
Import java.util.*
Public class IntersectionTest2 {public static void main (String [] args) {int [] nums1 = {1,2,2,1}; int [] nums2 = {2,2}; int [] intersection = intersection (nums1, nums2); for (int num: intersection) {System.out.print (num + "\ t");}}
Public static int [] intersection (int [] nums1, int [] nums2) {if (nums1 = = null | | nums1.length = = 0 | | nums2 = = null | | nums2.length = = 0) {return new int [0];} Set set = new HashSet (nums1.length); for (int num: nums1) {set.add (num);} Set set2 = new HashSet (nums2.length) For (int num: nums2) {set2.add (num);} set.retainAll (set2); int [] result = new int [set.size ()]; Iterator iterator = set.iterator (); int index = 0; while (iterator.hasNext ()) {result [index++] = iterator.next ();} return result }}
The above is how to find the intersection of two arrays in LeetCode. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.