@@ -32,15 +32,15 @@ class Solution:
32
32
def smallestDifference (self , a : List[int ], b : List[int ]) -> int :
33
33
a.sort()
34
34
b.sort()
35
- i, j, res = 0 , 0 , 2147483647
36
- m, n = len (a), len (b)
37
- while i < m and j < n:
38
- if a[i] == b[j]: return 0
35
+ i = j = 0
36
+ res = float (' inf' )
37
+ while i < len (a) and j < len (b):
39
38
res = min (res, abs (a[i] - b[j]))
40
- if a[i] > b[j]: j += 1
41
- else : i += 1
39
+ if a[i] > b[j]:
40
+ j += 1
41
+ else :
42
+ i += 1
42
43
return res
43
-
44
44
```
45
45
46
46
### ** Java**
@@ -52,17 +52,71 @@ class Solution {
52
52
public int smallestDifference (int [] a , int [] b ) {
53
53
Arrays . sort(a);
54
54
Arrays . sort(b);
55
- int m = a. length, n = b. length;
56
55
int i = 0 , j = 0 ;
57
56
long res = Long . MAX_VALUE ;
58
- while (i < m && j < n) {
59
- if (a[i] == b[j]) return 0 ;
57
+ while (i < a. length && j < b. length) {
60
58
res = Math . min(res, Math . abs((long ) a[i] - (long ) b[j]));
59
+ if (a[i] > b[j]) {
60
+ ++ j;
61
+ } else {
62
+ ++ i;
63
+ }
64
+ }
65
+ return (int ) res;
66
+ }
67
+ }
68
+ ```
69
+
70
+ ### ** C++**
71
+
72
+ ``` cpp
73
+ class Solution {
74
+ public:
75
+ int smallestDifference(vector<int >& a, vector<int >& b) {
76
+ sort(a.begin(), a.end());
77
+ sort(b.begin(), b.end());
78
+ int i = 0, j = 0;
79
+ long res = LONG_MAX;
80
+ while (i < a.size() && j < b.size()) {
81
+ res = min(res, abs((long)a[ i] - (long)b[ j] ));
61
82
if (a[ i] > b[ j] ) ++j;
62
83
else ++i;
63
84
}
64
- return ( int ) res;
85
+ return res;
65
86
}
87
+ };
88
+ ```
89
+
90
+ ### **Go**
91
+
92
+ ```go
93
+ func smallestDifference(a []int, b []int) int {
94
+ sort.Ints(a)
95
+ sort.Ints(b)
96
+ i, j, res := 0, 0, 2147483647
97
+ for i < len(a) && j < len(b) {
98
+ res = min(res, abs(a[i]-b[j]))
99
+ if a[i] > b[j] {
100
+ j++
101
+ } else {
102
+ i++
103
+ }
104
+ }
105
+ return res
106
+ }
107
+
108
+ func abs(a int) int {
109
+ if a < 0 {
110
+ return -a
111
+ }
112
+ return a
113
+ }
114
+
115
+ func min(a, b int) int {
116
+ if a < b {
117
+ return a
118
+ }
119
+ return b
66
120
}
67
121
```
68
122
0 commit comments