-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathFormSmallestNumberFromTwoDigitArrays.java
58 lines (50 loc) · 1.68 KB
/
FormSmallestNumberFromTwoDigitArrays.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
51
52
53
54
55
56
57
58
// https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays
// T: O(N log(N) + M log(M))
// S: O(log(N) + log(M))
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class FormSmallestNumberFromTwoDigitArrays {
public int minNumber(int[] nums1, int[] nums2) {
final Set<Integer> intersection = intersection(nums1, nums2);
if (!intersection.isEmpty()) {
final int[] digits = toArray(intersection);
Arrays.sort(digits);
return digits[0];
}
Arrays.sort(nums1);
Arrays.sort(nums2);
final int smallerDigit = Math.min(nums1[0], nums2[0]);
final int largerDigit = Math.max(nums1[0], nums2[0]);
return smallerDigit * 10 + largerDigit;
}
private Set<Integer> intersection(int[] array1, int[] array2) {
final Set<Integer> set1 = toSet(array1);
final Set<Integer> set2 = toSet(array2);
return intersection(set1, set2);
}
private Set<Integer> toSet(int[] array) {
final Set<Integer> set = new HashSet<>();
for (int element : array) {
set.add(element);
}
return set;
}
private Set<Integer> intersection(Set<Integer> set1, Set<Integer> set2) {
final Set<Integer> set = new HashSet<>();
for (int element : set1) {
if (set2.contains(element)) {
set.add(element);
}
}
return set;
}
private int[] toArray(Set<Integer> set) {
final int[] array = new int[set.size()];
int index = 0;
for (int element : set) {
array[index++] = element;
}
return array;
}
}