29
29
<!-- 这里可写当前语言的特殊实现逻辑 -->
30
30
31
31
``` python
32
-
32
+ class Solution :
33
+ def findClosest (self , words : List[str ], word1 : str , word2 : str ) -> int :
34
+ idx1, idx2, ans = 10 ** 5 , - 10 ** 5 , 10 ** 5
35
+ for i, word in enumerate (words):
36
+ if word == word1:
37
+ idx1 = i
38
+ elif word == word2:
39
+ idx2 = i
40
+ ans = min (ans, abs (idx1 - idx2))
41
+ return ans
33
42
```
34
43
35
44
### ** Java**
36
45
37
46
<!-- 这里可写当前语言的特殊实现逻辑 -->
38
47
39
48
``` java
40
-
49
+ class Solution {
50
+ public int findClosest (String [] words , String word1 , String word2 ) {
51
+ int idx1 = 100000 ;
52
+ int idx2 = - 100000 ;
53
+ int ans = 100000 ;
54
+ for (int i = 0 ; i < words. length; ++ i) {
55
+ String word = words[i];
56
+ if (word. equals(word1)) {
57
+ idx1 = i;
58
+ } else if (word. equals(word2)) {
59
+ idx2 = i;
60
+ }
61
+ ans = Math . min(ans, Math . abs(idx1 - idx2));
62
+ }
63
+ return ans;
64
+ }
65
+ }
41
66
```
42
67
43
68
### ** TypeScript**
@@ -61,6 +86,56 @@ function findClosest(words: string[], word1: string, word2: string): number {
61
86
}
62
87
```
63
88
89
+ ### ** C++**
90
+
91
+ ``` cpp
92
+ class Solution {
93
+ public:
94
+ int findClosest(vector<string >& words, string word1, string word2) {
95
+ int idx1 = 1e5, idx2 = -1e5, ans = 1e5;
96
+ for (int i = 0; i < words.size(); ++i)
97
+ {
98
+ string word = words[ i] ;
99
+ if (word == word1) idx1 = i;
100
+ else if (word == word2) idx2 = i;
101
+ ans = min(ans, abs(idx1 - idx2));
102
+ }
103
+ return ans;
104
+ }
105
+ };
106
+ ```
107
+
108
+ ### **Go**
109
+
110
+ ```go
111
+ func findClosest(words []string, word1 string, word2 string) int {
112
+ idx1, idx2, ans := 100000, -100000, 100000
113
+ for i, word := range words {
114
+ if word == word1 {
115
+ idx1 = i
116
+ } else if word == word2 {
117
+ idx2 = i
118
+ }
119
+ ans = min(ans, abs(idx1-idx2))
120
+ }
121
+ return ans
122
+ }
123
+
124
+ func min(a, b int) int {
125
+ if a < b {
126
+ return a
127
+ }
128
+ return b
129
+ }
130
+
131
+ func abs(x int) int {
132
+ if x < 0 {
133
+ return -x
134
+ }
135
+ return x
136
+ }
137
+ ```
138
+
64
139
### ** ...**
65
140
66
141
```
0 commit comments