Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to find the intersection of two arrays in LeetCode

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report