LeetCode-面试题 08.03. 魔术索引

LeetCode-面试题 08.03. 魔术索引

题目

魔术索引。 在数组A[0...n-1]中,有所谓的魔术索引,满足条件A[i] = i。给定一个有序整数数组,编写一种方法找出魔术索引,若有的话,在数组A中找出一个魔术索引,如果没有,则返回-1。若有多个魔术索引,返回索引值最小的一个。

示例1:

输入:nums = [0, 2, 3, 4, 5]
输出:0
说明: 0下标的元素为0
示例2:

输入:nums = [1, 1, 1]
输出:1

思路

很容易就能想到用二分法,不过我做的比较纠结,因为我一开始设置二分条件时,没有考虑到数组中存在相同的数字的情况,导致卡在相同数字这里很久,特殊情况和边界条件真的非常重要呀;

代码

class Solution {
public:
    int binarySearch(vector<int>& nums, int low, int high) {
        int mid = (low+high)/2, ret = 0;
        if (low+1 == high) {
            if (low == nums[low]) return low;
            if (high == nums[high]) return high;
            return -1;
        }

        if (nums[low] >= high || nums[high] <= low) return -1; 

        if (nums[mid] == mid) {
            ret = binarySearch(nums, low, mid);
            if (ret == -1) return mid;
            else return ret;
        } else {
            ret = binarySearch(nums, low, mid);
            if (ret == -1) return binarySearch(nums, mid, high);
            else return ret;
        }
        return -1;
    }

    int findMagicIndex(vector<int>& nums) {
       int numsLength = nums.size();
       if (numsLength == 0) return -1; 
       if (numsLength == 1) return (nums[0]==0?0:-1);
       return binarySearch(nums, 0, numsLength-1);
    }
};
原文地址:https://www.cnblogs.com/sakurapiggy/p/13411973.html