-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPermCheck.js
More file actions
63 lines (34 loc) · 896 Bytes
/
Copy pathPermCheck.js
File metadata and controls
63 lines (34 loc) · 896 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 4. PermCheck
// Problem:
// Check whether an array is a permutation of integers 1..N.
// Example:
// Input: [4, 1, 3, 2]
// Output: 1 (true, it's a permutation)
// Input: [4, 1, 3]
// Output: 0 (false, missing 2)
// Solution Idea:
// Use a set or summation comparison to check if the array contains exactly all numbers from 1...N.
// Time Complexity: O(n).
// javascript
// Copy code
function permCheck(A){
const n = A.length;
const set = new Set(A);
let max = -Infinity;
for(let i=0; i < A.length; i++){
if(A[i] > max ){
max = A[i];
}
if(set.size === n && max === n){
return 1;
}
else{
return 0;
}
}
}
function permCheck(A) {
const n = A.length;
const set = new Set(A);
return set.size === n && Math.max(...A) === n ? 1 : 0;
}