java 用max函数,java或python中一个范围的递归max函数

我有一个来自“思考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的语言中。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值