面试题 08.03. 魔术索引 [easy]
面试题 08.03. 魔术索引 [easy]
https://leetcode-cn.com/problems/magic-index-lcci/
魔术索引。 在数组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
说明:
- nums长度在[1, 1000000]之间
- 此题为原书中的 Follow-up,即数组中可能包含重复元素的版本
通过次数33,966提交次数49,760
First Try
2020-07-31
数组有重复,因此遇到idx和nums[idx]谁大谁小的时候都不能直接跳出,还是得一路比较下去等着追上来。但可以用快速横跳提高一点速度。
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
idx, n = 0, len(nums)
while idx < n:
if idx == nums[idx]:
return idx
idx = max(idx + 1, nums[idx + 1])
return -1
- 执行用时:36 ms, 在所有 Python3 提交中击败了96.46%的用户
- 内存消耗:14.3 MB, 在所有 Python3 提交中击败了50.00%的用户