[AlgoExpert] Index Equals Value

Index Equals Value

  • Time : O(logn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int binarySearch(vector<int> array) {
int l = 0, r = array.size() - 1, res = INT_MAX;
while(l <= r) {
int m = (l + r) / 2;
if(array[m] == m) res = min(res, m);

if(array[m] >= m) r = m - 1;
else l = m + 1;
}
return res == INT_MAX ? -1 : res;
}

int iterationSearch(vector<int> array) {
for(int i = 0; i < array.size(); i++)
if(i == array[i]) return i;
return -1;
}

int indexEqualsValue(vector<int> array) {
return array.size() > 32 ? binarySearch(array) : iterationSearch(array);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/index-equals-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.