0%

面试题 08.03. 魔术索引

1. 顺序遍历

逐个判断,时间O(n),空间O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findMagicIndex(vector<int>& nums) {
int n = nums.size();
int ans = -1;
for (int i = 0; i < n; i++) {
if (i == nums[i]) {
ans = i;
break;
}
}

return ans;
}
};