File tree 3 files changed +81
-0
lines changed
3 files changed +81
-0
lines changed Original file line number Diff line number Diff line change @@ -165,6 +165,60 @@ var twoSum = function (nums, target) {
165
165
};
166
166
```
167
167
168
+ ### ** TypeScript**
169
+
170
+ 哈希表:
171
+
172
+ ``` ts
173
+ function twoSum(nums : number [], target : number ): number [] {
174
+ const set = new Set ();
175
+ for (const num of nums ) {
176
+ if (set .has (target - num )) {
177
+ return [target - num , num ]
178
+ }
179
+ set .add (num )
180
+ }
181
+ return null
182
+ };
183
+ ```
184
+
185
+ 双指针:
186
+
187
+ ``` ts
188
+ function twoSum(nums : number [], target : number ): number [] {
189
+ let l = 0 ;
190
+ let r = nums .length - 1 ;
191
+ while (nums [l ] + nums [r ] !== target ) {
192
+ if (nums [l ] + nums [r ] < target ) {
193
+ l ++ ;
194
+ } else {
195
+ r -- ;
196
+ }
197
+ }
198
+ return [nums [l ], nums [r ]];
199
+ }
200
+ ```
201
+
202
+ ### ** Rust**
203
+
204
+ ``` rust
205
+ use std :: cmp :: Ordering ;
206
+
207
+ impl Solution {
208
+ pub fn two_sum (nums : Vec <i32 >, target : i32 ) -> Vec <i32 > {
209
+ let mut l = 0 ;
210
+ let mut r = nums . len () - 1 ;
211
+ loop {
212
+ match target . cmp (& (nums [l ] + nums [r ])) {
213
+ Ordering :: Less => r -= 1 ,
214
+ Ordering :: Greater => l += 1 ,
215
+ Ordering :: Equal => break vec! [nums [l ], nums [r ]],
216
+ }
217
+ }
218
+ }
219
+ }
220
+ ```
221
+
168
222
### ** ...**
169
223
170
224
```
Original file line number Diff line number Diff line change
1
+ use std:: cmp:: Ordering ;
2
+
3
+ impl Solution {
4
+ pub fn two_sum ( nums : Vec < i32 > , target : i32 ) -> Vec < i32 > {
5
+ let mut l = 0 ;
6
+ let mut r = nums. len ( ) - 1 ;
7
+ loop {
8
+ match target. cmp ( & ( nums[ l] + nums[ r] ) ) {
9
+ Ordering :: Less => r -= 1 ,
10
+ Ordering :: Greater => l += 1 ,
11
+ Ordering :: Equal => break vec ! [ nums[ l] , nums[ r] ] ,
12
+ }
13
+ }
14
+ }
15
+ }
Original file line number Diff line number Diff line change
1
+ function twoSum ( nums : number [ ] , target : number ) : number [ ] {
2
+ let l = 0 ;
3
+ let r = nums . length - 1 ;
4
+ while ( nums [ l ] + nums [ r ] !== target ) {
5
+ if ( nums [ l ] + nums [ r ] < target ) {
6
+ l ++ ;
7
+ } else {
8
+ r -- ;
9
+ }
10
+ }
11
+ return [ nums [ l ] , nums [ r ] ] ;
12
+ }
You can’t perform that action at this time.
0 commit comments