AcWing 69. 数组中数值和下标相等的元素(暴力和二分)
原题链接
简单
作者:
零邪sword
,
2021-04-09 19:23:41
,
所有人可见
,
阅读 254
算法1
暴力枚举
18ms
class Solution {
public:
int getNumberSameAsIndex(vector<int>& nums) {
for (int i = 0; i < nums.size(); i ++ )
if (nums[i] == i) return i;
return -1;
}
};
算法2
二分查找
22ms
class Solution {
public:
int getNumberSameAsIndex(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while(l<r)
{
int mid = l + r >> 1;
if (nums[mid] >= mid) r = mid;
else l = mid + 1;
}
if(nums[r] == r) return r;
else return -1;
}
};