Easy
暴力解法思路比较清晰:遍历数组,遇到索引和值相同的情况返回
python3
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
for i,v in enumerate(nums):
if i == v:
return i
return -1
应为数组是有序的,我们想到能不能用二分方法去做。
最坏情况也是\(O(n)\)
以上,尝试写一下代码,AC!
python3
class Solution:
def helper(self,start,end,nums):
if start > end:
return -1
mid = start + (end-start) // 2
if mid == nums[mid]:
return mid
l_res = self.helper(start,mid-1,nums)
if l_res == -1:
return self.helper(mid+1,end,nums)
else:
return l_res
def findMagicIndex(self, nums: List[int]) -> int:
return self.helper(0, len(nums)-1, nums)