forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
50 lines (40 loc) · 1.38 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
/// Author : liuyubobobo
/// Time : 2017-11-14
import java.util.HashMap;
import java.util.ArrayList;
/// Using Hash Map
/// Time Complexity: O(len(nums1) + len(nums2)*log(len(nums1)))
/// Space Complexity: O(len(nums1))
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int num: nums1)
if(!record.containsKey(num))
record.put(num, 1);
else
record.put(num, record.get(num) + 1);
ArrayList<Integer> result = new ArrayList<Integer>();
for(int num: nums2)
if(record.containsKey(num) && record.get(num) > 0){
result.add(num);
record.put(num, record.get(num) - 1);
}
int[] ret = new int[result.size()];
int index = 0;
for(Integer num: result)
ret[index++] = num;
return ret;
}
private static void printArr(int[] arr){
for(int e: arr)
System.out.print(e + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 2, 1};
int[] nums2 = {2, 2};
int[] res = (new Solution()).intersect(nums1, nums2);
printArr(res);
}
}