File tree 1 file changed +37
-12
lines changed
scripts/algorithms/A/Arithmetic Subarrays
1 file changed +37
-12
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 84 ms (Top 88.87%) | Memory: 49.20 MB (Top 18.22%)
2
+
1
3
/**
2
4
* @param {number[] } nums
3
5
* @param {number[] } l
4
6
* @param {number[] } r
5
7
* @return {boolean[] }
6
8
*/
7
- var checkArithmeticSubarrays = function ( nums , l , r ) {
9
+ var checkArithmeticSubarrays = function ( nums , l , r ) {
8
10
let result = [ ] ;
9
- for ( let i = 0 ; i < l . length ; i ++ ) {
10
- let subNums = [ ...nums ] . slice ( l [ i ] , r [ i ] + 1 ) ;
11
- subNums = subNums . sort ( ( a , b ) => a - b ) ;
12
- let diff = subNums [ 1 ] - subNums [ 0 ] ;
13
- let s = true
14
- for ( let j = 0 ; j < subNums . length - 1 ; j ++ ) {
15
- if ( ! ( subNums [ j + 1 ] - subNums [ j ] == diff ) )
16
- s = false
17
- }
18
- result . push ( s )
11
+ for ( let i = 0 ; i < l . length ; i ++ ) {
12
+ result . push ( isArithmetic ( nums . slice ( l [ i ] , r [ i ] + 1 ) ) ) ;
19
13
}
20
- return result
14
+ return result ;
21
15
} ;
22
16
17
+ function isArithmetic ( arr ) {
18
+ let min = Math . min ( ...arr ) ;
19
+ let max = Math . max ( ...arr ) ;
20
+
21
+ if ( min == max ) {
22
+ return true ;
23
+ }
24
+
25
+ let step = ( max - min ) / ( arr . length - 1 ) ;
26
+
27
+ if ( step != Math . floor ( step ) ) {
28
+ return false ;
29
+ }
30
+
31
+ let set = new Set ( ) ;
32
+ for ( let x of arr ) {
33
+ if ( set . has ( x ) ) {
34
+ return false ;
35
+ }
36
+
37
+ set . add ( x ) ;
38
+ }
39
+
40
+ for ( let x = min ; x <= max ; x += step ) {
41
+ if ( ! set . has ( x ) ) {
42
+ return false ;
43
+ }
44
+ }
45
+
46
+ return true ;
47
+ }
You can’t perform that action at this time.
0 commit comments