题目:

魔术索引。 在数组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

分析:

没有想出来二分法,不过使用了一点小优化,还是从0索引开始遍历,不过当前索引指向的元素如果大于当前索引的话,下次遍历就从该元素处遍历,因为数组是有序的,意味着至少到该元素处才有可能出现魔术索引。

程序:

class Solution {
    public int findMagicIndex(int[] nums) {
        int index = 0;
        while(index < nums.length){
            if(nums[index] == index)
                return index;
            if(nums[index] > index)
                index = nums[index];
            else
                index++;
        }
        return -1;
    }
}

 

相关文章:

  • 2021-11-14
  • 2021-10-18
  • 2021-10-09
  • 2021-08-18
  • 2021-10-09
  • 2021-05-22
  • 2022-01-20
  • 2021-06-06
猜你喜欢
  • 2021-07-22
  • 2021-12-12
  • 2021-12-31
  • 2021-09-21
  • 2021-07-06
  • 2021-11-06
  • 2022-01-29
相关资源
相似解决方案