我有一个来自“思考java,如何像计算机科学家一样思考”的练习Write a method called maxInRange that takes an array of integers
and a range of indices (lowIndex and highIndex), and that finds the
maximum value in the array, considering only the elements between
lowIndex and highIndex, including both ends.
This method should be recursive. If the length of the range is 1, that is,
if lowIndex == highIndex, we know immediately that the sole element
in the range must be the maximum. So that's the base case.
If there is more than one element in the range, we can break the array
into two pieces, find the maximum in each of the pieces, and then find
the maximum of the maxima.
我用python给出了一个非常接近但非常不准确的答案:cycles=0
def max_in_range(lst,low,high):
'''
Could not be able to make it work correctly
'''
global cycles
cycles+=1
if low==high:
#print "Cycles: ",cycles
return lst
else:
max_left=max_in_range(lst[low:len(lst)/2+1],low+1,high)
max_right=max_in_range(lst[len(lst)/2:len(lst)],low+1,high)
return max_right if max_right>max_left else max_left
lst=[112,32,45,71238,9999,45,12,6,3] # always Returns the mid element.
print max_in_range(lst,0,10)
def max(lst):
global cycles
cycles+=1
if len(lst)==1:
print "Cycles: ",cycles
return lst[0]
else:
m=max(lst[1:])
return m if m> lst[0] else lst[0]
print max(lst)
max函数与问题所需的功能相比非常简单,即函数
递归,有两个限制,在运行时拆分列表。max_in_range函数始终返回数组中的中间元素,即9999。
我需要一些关于如何满足问题要求的建议。在Java或Python或其他类似C的语言中。在