Skip to content

Commit c731f4b

Browse files
committed
Runtime: 84 ms (Top 88.87%) | Memory: 49.20 MB (Top 18.22%)
1 parent 06e2adc commit c731f4b

File tree

1 file changed

+37
-12
lines changed

1 file changed

+37
-12
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,47 @@
1+
// Runtime: 84 ms (Top 88.87%) | Memory: 49.20 MB (Top 18.22%)
2+
13
/**
24
* @param {number[]} nums
35
* @param {number[]} l
46
* @param {number[]} r
57
* @return {boolean[]}
68
*/
7-
var checkArithmeticSubarrays = function(nums, l, r) {
9+
var checkArithmeticSubarrays = function(nums, l, r) {
810
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)));
1913
}
20-
return result
14+
return result;
2115
};
2216

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+
}

0 commit comments

Comments
 (0)