[LeetCode] Fixed Point

1064. Fixed Point

Given an array of distinct integers arr, where arr is sorted in ascending order, return the smallest index i that satisfies arr[i] == i. If there is no such index, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int fixedPoint(vector<int>& arr) {
int index = lower_bound(arr.begin(), arr.end(), 0) - arr.begin();

while(index < arr.size()) {
if(index == arr[index]) return index;
else if(index > arr[index]) index++;
else index = arr[index] + 1;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/22/PS/LeetCode/fixed-point/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.