From 20a518c856320d0faa53e12664120bef5ba8a53c Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:53:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00349.=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0349.两个数组的交集.md | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index c196b467..75ef9061 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -75,7 +75,37 @@ public: Java: +```Java +import java.util.HashSet; +import java.util.Set; +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) { + return new int[0]; + } + Set set1 = new HashSet<>(); + Set resSet = new HashSet<>(); + //遍历数组1 + for (int i : nums1) { + set1.add(i); + } + //遍历数组2的过程中判断哈希表中是否存在该元素 + for (int i : nums2) { + if (set1.contains(i)) { + resSet.add(i); + } + } + int[] resArr = new int[resSet.size()]; + int index = 0; + //将结果几何转为数组 + for (int i : resSet) { + resArr[index++] = i; + } + return resArr; + } +} +``` Python: