File tree 3 files changed +63
-0
lines changed
3 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -137,6 +137,28 @@ impl Solution {
137
137
}
138
138
```
139
139
140
+ ``` swift
141
+ class Solution {
142
+ func findClosest (_ words : [String ], _ word1 : String , _ word2 : String ) -> Int {
143
+ let inf = Int .max / 2
144
+ var i = inf
145
+ var j = - inf
146
+ var ans = inf
147
+
148
+ for (k, word) in words.enumerated () {
149
+ if word == word1 {
150
+ i = k
151
+ } else if word == word2 {
152
+ j = k
153
+ }
154
+ ans = min (ans, abs (i - j))
155
+ }
156
+
157
+ return ans
158
+ }
159
+ }
160
+ ```
161
+
140
162
<!-- tabs: end -->
141
163
142
164
### 方法二:哈希表 + 双指针
Original file line number Diff line number Diff line change @@ -139,6 +139,28 @@ impl Solution {
139
139
}
140
140
```
141
141
142
+ ``` swift
143
+ class Solution {
144
+ func findClosest (_ words : [String ], _ word1 : String , _ word2 : String ) -> Int {
145
+ let inf = Int .max / 2
146
+ var i = inf
147
+ var j = - inf
148
+ var ans = inf
149
+
150
+ for (k, word) in words.enumerated () {
151
+ if word == word1 {
152
+ i = k
153
+ } else if word == word2 {
154
+ j = k
155
+ }
156
+ ans = min (ans, abs (i - j))
157
+ }
158
+
159
+ return ans
160
+ }
161
+ }
162
+ ```
163
+
142
164
<!-- tabs: end -->
143
165
144
166
### Solution 2: Hash Table + Two Pointers
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func findClosest( _ words: [ String ] , _ word1: String , _ word2: String ) -> Int {
3
+ let inf = Int . max / 2
4
+ var i = inf
5
+ var j = - inf
6
+ var ans = inf
7
+
8
+ for (k, word) in words. enumerated ( ) {
9
+ if word == word1 {
10
+ i = k
11
+ } else if word == word2 {
12
+ j = k
13
+ }
14
+ ans = min ( ans, abs ( i - j) )
15
+ }
16
+
17
+ return ans
18
+ }
19
+ }
You can’t perform that action at this time.
0 commit comments