Title Description: Given two arrays to seek their public part, the output form is an array, the same element is just output once for example:
NUMS1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Original Description:
Given the arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must is unique.
The result can be on any order.
Idea One:
1. Using HashMap (Integer,boolean) data structure, the first is to facilitate Array1, put into MAP1
2. Traverse the Array2 to determine if the MAP1 is included and deposited MAP2
3. Remove the MAP2 data and save the array output
Code:
Public class solution { /** * @param nums1 an integer array * @param nums2 an integer array * @return A N Integer array * / Public int[]intersection(int[] nums1,int[] nums2) {hashmap<integer, boolean> map1 =NewHashmap<integer, boolean> (); Hashmap<integer, boolean> intersectmap =NewHashmap<integer, boolean> (); for(inti =0; i < nums1.length; i++) {if(!map1.containskey (Nums1[i])) {Map1.put (Nums1[i],true); } } for(intj =0; J < Nums2.length; J + +) {if(Map1.containskey (Nums2[j]) &&!intersectmap.containskey (Nums2[j])) {Intersectmap.put (nums2[j],true); } }int[] result =New int[Intersectmap.size ()];inti =0; for(Integer E:intersectmap.keyset ()) {Result[i] = e; i++; }returnResult }}
Idea two:
- Sort the two arrays first
- Index I,J represents Array1 and Array2, respectively, plus 1, who is small who corresponds to the index plus 1
-
Code:
Public class solution { /** * @param nums1 an integer array * @param nums2 an integer array * @return A N Integer array * / Public int[]intersection(int[] nums1,int[] nums2) {arrays.sort (NUMS1); Arrays.sort (NUMS2);inti =0, j =0;int[] temp =New int[Nums1.length];intindex =0; while(I < Nums1.length && J < Nums2.length) {if(Nums1[i] = = Nums2[j]) {if(Index = =0|| Temp[index-1] = Nums1[i]) {temp[index++] = Nums1[i]; } i++; j + +; }Else if(Nums1[i] < nums2[j]) {i++; }Else{j + +; } }int[] result =New int[index]; for(intK =0; K < index; k++) {Result[k] = temp[k]; }returnResult }}
For more leetcode topics, please see my leetcode column. The links are as follows:
Leetcode column
My QR code is as follows, welcome to exchange discussion
You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:
"Leetcode75" intersection of Arrays (intersection of arrays)