我正在从破解编码面试的书中解决这个问题:
9.3.数组A [0 ... n-1]中的魔术索引被定义为索引,使得A [i] = i.给定一个不同整数的排序数组,编写一个方法来查找数组A中的魔术索引(如果存在).
这是我的代码:
def magic_index(seq, start = None, end = None):
if start is None:
start = 0
if end is None:
end = len(seq) - 1
if start > end:
return -1
index = (start + end) // 2
if index == seq(index):
print("Equal to index. Value of index = " + index)
return index
if index > seq[index]:
print("Greater than loop. Value of Index =" + index)
return magic_index(seq, start=index + 1, …Run Code Online (Sandbox Code Playgroud) python ×1