LeetCode Interview Question 08.03. Magic Index

Article directory

1. Title

  Magic Index. In arrays A[0...n-1], there are so-called magic indexes, which satisfy conditions A[i] = i. Given a sorted array of integers, write a method to find the magic index in array A, if any, and return -1 if there is none. If there are multiple magic indexes, the one with the smallest index value is returned.

Example 1:

Input: nums = [0, 2, 3, 4, 5]
Output: 0
Description: The element with subscript 0 is 0

Example 2:

Input: nums = [1, 1, 1]
Output: 1

illustrate:

  • The length of nums is between [1, 1000000]
  • This title is Follow-up in the original book, which is a version in which the array may contain duplicate elements.

  Click here to jump to the question .

2. C# problem solution

  Traverse in sequence, but prune: if the current value is greater than the index, jump to the index position of the current value.

public class Solution {
    
    
    public int FindMagicIndex(int[] nums) {
    
    
        if (nums[0] > nums.Length || nums[^1] < 0) return -1;
        int i = 0;
        while (i < nums.Length) {
    
    
            if (nums[i] == i) return i;   // 找到魔术索引,立即返回
            if (nums[i] > i) i = nums[i]; // 如果当前值大于索引,则跳转到当前值的索引位置
            else i++;                     // 否则,继续判断下一个位置
        }
        return -1;
    }
}
  • Time: 88 ms, beating 81.82% of users using C#
  • Memory: 41.7 MB, beats 72.73% of users using C#

Guess you like

Origin blog.csdn.net/zheliku/article/details/133527813