【发布时间】:2018-11-16 17:02:48
【问题描述】:
给定一个先增后减的n个整数的山序列,找到山顶。
例子
给定 nums = [1, 2, 4, 8, 6, 3] 返回 8
给定 nums = [10, 9, 8, 7],返回 10
class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountainSequence(self, nums):
# write your code here
if nums == []:
return None
if len(nums) <= 1:
return nums[0]
elif len(nums) <= 2:
return max(nums[0], nums[1])
for i in range(len(nums) -2):
if nums[i] >= nums[i + 1]:
return nums[i]
return nums[-1]
它停留在 [3,5,3]。根据我的分析,运行for循环后出错了。但我不知道为什么 for 循环失败了。
【问题讨论】:
-
假设你不尝试二分搜索(也许你应该);为什么不只是
max(nums)? -
10 不是一座山——它事先不增加,之后减少
-
高原怎么样:
7, 8, 9, 9, 9, 8, 7? -
实际上不允许使用 max()。我只是懒得再写一些如果。哈哈
-
您为 range 函数提供了错误的参数,并且循环缺少一个元素。将其更改为
range(len(nums) - 1)。
标签: python-3.x for-loop