-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElementIndexEquality.js
93 lines (77 loc) · 2.21 KB
/
ElementIndexEquality.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//TASK
// Given a sorted array of distinct integers, write a function indexEqualsValue that returns the lowest index for which array[index] == index.
// Return -1 if there is no such index.
// Your algorithm should be very performant.
// [input] array of integers ( with 0-based nonnegative indexing )
// [output] integer
// Random Tests Constraints:
// Array length: 200 000
// Amount of tests: 1 000
// Time limit: 150 ms
//-----------------------------------------------------------------------
// -------------------Option #1 -------------------
//for..of cycle (by values)
// function IndexMatch(myArr) {
// for (var v of myArr) {
// if (v === myArr.indexOf(v)) {
// return myArr.indexOf(v);
// }
// }
// return -1
// }
// -------------------Option #2 -------------------
//for cycle (by indices)
// function IndexMatch(a) {
// for (let i=0;i>=a[i];i++) {
// if (i === a.indexOf(i)) {
// return a.indexOf(i);
// }
// }
// return -1
// }
// -------------------Option #3 -------------------
//find()
// function IndexMatch(arr) {
// let x=arr.find(el => el===arr.indexOf(el));
// return (x===undefined)?(-1):arr.indexOf(x);
// }
// -------------------Option #4 -------------------
///binary search
// function IndexMatch(a) {
// let s = 0;
// let e = a.length;
// let m;
// let x;
// //console.log(x);
// while (s <= e) {
// m = Math.floor((s + e) / 2);
// if (a[m] < m) {
// s = m + 1;
// } else if (a[m] >= m){
// if (a[m] === m){x=m;}
// e = m - 1;
// }
// }
// return (x===undefined)?(-1):x;
// }
// -------------------Option #5 -------------------
///binary search(compact)
function IndexMatch(a) {
let s = 0;
let e = a.length - 1;
let m;
while (s < e) {
m = Math.floor((s + e) / 2);
if (a[m] >= m) {
e = m;
} else {
s = m + 1;
}
}
return a[e] === e ? e : -1;
}
///test input
console.log(IndexMatch([-3, 0, 1, 3, 10])); //3
console.log(IndexMatch([-1, 0, 3, 6])); //-1
console.log(IndexMatch([-5, 1, 2, 3, 4, 5, 7, 10, 15])); //1
console.log(IndexMatch([-15, 0, -1, 2, 4, 5, 7, 10, 15])); //4