69. 数组中数值和下标相等的元素

class Solution {
public:
    int getNumberSameAsIndex(vector<int>& nums) {
        int n = nums.size();
        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[l] != l) return -1;
        return l;
    }
};
class Solution {
public:
    int getNumberSameAsIndex(vector<int>& nums) {
        int n = nums.size();
        int l = 0, r = nums.size() - 1;
        while (l < r) {
            int mid = l + r + 1 >> 1;
            if (nums[mid] <= mid) l = mid;
            else r = mid - 1;
        }
        
        if (nums[l] != l) return -1;
        return l;
    }
};
上一篇:用类名传递参数时一定要加括号


下一篇:OSPF附录E