File tree 1 file changed +33
-22
lines changed
solution/2700-2799/2799.Count Complete Subarrays in an Array
1 file changed +33
-22
lines changed Original file line number Diff line number Diff line change @@ -186,23 +186,28 @@ function countCompleteSubarrays(nums: number[]): number {
186
186
187
187
``` rust
188
188
use std :: collections :: HashSet ;
189
+
189
190
impl Solution {
190
191
pub fn count_complete_subarrays (nums : Vec <i32 >) -> i32 {
191
- let mut set : HashSet <& i32 > = nums . iter (). collect ();
192
+ let mut s = HashSet :: new ();
193
+ for & x in & nums {
194
+ s . insert (x );
195
+ }
196
+ let cnt = s . len ();
192
197
let n = nums . len ();
193
- let m = set . len ();
194
198
let mut ans = 0 ;
199
+
195
200
for i in 0 .. n {
196
- set . clear ();
201
+ s . clear ();
197
202
for j in i .. n {
198
- set . insert (& nums [j ]);
199
- if set . len () == m {
200
- ans += n - j ;
201
- break ;
203
+ s . insert (nums [j ]);
204
+ if s . len () == cnt {
205
+ ans += 1 ;
202
206
}
203
207
}
204
208
}
205
- ans as i32
209
+
210
+ ans
206
211
}
207
212
}
208
213
```
@@ -358,27 +363,33 @@ function countCompleteSubarrays(nums: number[]): number {
358
363
359
364
``` rust
360
365
use std :: collections :: HashMap ;
361
- use std :: collections :: HashSet ;
366
+
362
367
impl Solution {
363
368
pub fn count_complete_subarrays (nums : Vec <i32 >) -> i32 {
364
- let n = nums . len ();
365
- let m = nums . iter (). collect :: <HashSet <& i32 >>(). len ();
366
- let mut map = HashMap :: new ();
369
+ let mut d = HashMap :: new ();
370
+ for & x in & nums {
371
+ d . insert (x , 1 );
372
+ }
373
+ let cnt = d . len ();
367
374
let mut ans = 0 ;
368
- let mut i = 0 ;
369
- for j in 0 .. n {
370
- * map . entry (nums [j ]). or_insert (0 ) += 1 ;
371
- while map . len () == m {
372
- ans += n - j ;
373
- let v = map . entry (nums [i ]). or_default ();
374
- * v -= 1 ;
375
- if * v == 0 {
376
- map . remove (& nums [i ]);
375
+ let n = nums . len ();
376
+ d . clear ();
377
+
378
+ let (mut i , mut j ) = (0 , 0 );
379
+ while j < n {
380
+ * d . entry (nums [j ]). or_insert (0 ) += 1 ;
381
+ while d . len () == cnt {
382
+ ans += (n - j ) as i32 ;
383
+ let e = d . get_mut (& nums [i ]). unwrap ();
384
+ * e -= 1 ;
385
+ if * e == 0 {
386
+ d . remove (& nums [i ]);
377
387
}
378
388
i += 1 ;
379
389
}
390
+ j += 1 ;
380
391
}
381
- ans as i32
392
+ ans
382
393
}
383
394
}
384
395
```
You can’t perform that action at this time.
0 commit comments