File tree Expand file tree Collapse file tree 1 file changed +33
-22
lines changed
solution/2700-2799/2799.Count Complete Subarrays in an Array Expand file tree Collapse file tree 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 {
186186
187187``` rust
188188use std :: collections :: HashSet ;
189+
189190impl Solution {
190191 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 ();
192197 let n = nums . len ();
193- let m = set . len ();
194198 let mut ans = 0 ;
199+
195200 for i in 0 .. n {
196- set . clear ();
201+ s . clear ();
197202 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 ;
202206 }
203207 }
204208 }
205- ans as i32
209+
210+ ans
206211 }
207212}
208213```
@@ -358,27 +363,33 @@ function countCompleteSubarrays(nums: number[]): number {
358363
359364``` rust
360365use std :: collections :: HashMap ;
361- use std :: collections :: HashSet ;
366+
362367impl Solution {
363368 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 ();
367374 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 ]);
377387 }
378388 i += 1 ;
379389 }
390+ j += 1 ;
380391 }
381- ans as i32
392+ ans
382393 }
383394}
384395```
You can’t perform that action at this time.
0 commit comments