Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the intersection of arrays

Shulou Source: shulou.com Published: 2022-06-01 05:21:05 09月30日 Update

This article introduces you how to use array intersection, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Algorithm:

To find the intersection of arrays, it is relatively easy to make use of the key,value feature of map. The steps are as follows:

1. First iterate through array 1, and then save the array to map1 2. 0. Traverse array 2 and store the array in map2. In the process of storage, you need to determine whether it exists in map1 or not, and do de-reprocessing or not according to the requirements of the topic. 3. Put the elements that meet the criteria into the new array. (note: if it is multiple arrays, you can find the intersection in pairs, and then decrease in turn until the number of arrays is 1.)

Topic 1:

Code implementation:

Func intersection (nums1 [] int, nums2 [] int) [] int {var numMap,numMap1 map [int] bool var tar [] int numMap = make (bool) numMap1 = make (map [bool]) for _, i:=range nums1 {/ / ergodic array 1 excludes duplicate numbers if _, v:=numMap [I] ! v {numMap [I] = true}} for _, j:=range nums2 {if _, v:=numMap1 [j];! v {/ / traversal array 2 excludes duplicate digits if _, v1:=numMap [j] V1 {/ / find the intersection of array 1 and array 2 numMap1 [j] = true tar = append (tar,j)} return tar}

Execution result:

Topic 2:

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

Code implementation:

Func intersect (nums1 [] int, nums2 [] int) [] int {if len (nums1) = = 0 | len (nums2) = 0 {return nil} var tar [] int nMap: = make (mapping [int] for _, n: = range nums1 {_ Ok: = nMap [n] if! ok {nMap [n] = 1} else {nmap [n] + +}} for _, m: = range nums2 {_, ok: = nMap [m] if ok & & nMap [m] > 0 {nMap [m]-tar = append (tar,m)}} return tar}

Execution result:

On how to use the intersection of arrays to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Array intersection topic code content number more result processing help good number element interest remarks multiple guys buddies articles conditions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Information Huawei Apple NVidia