尋找峯值(leetcode)

&emps;峯值元素是指其值大於左右相鄰值的元素。
給定一個輸入數組nums,其中nums[i] ≠ nums[i+1],找到峯值元素並輸出其索引值,
你可以假設nums[-1] = nums[n] = -∞。
注意:不用擔心存在多個峯值,測試數據保證僅存在一個峯值

Input
輸入一個整數n,表述數組的長度,接下來依次輸入n個數字,表示數組元素的值
Output
輸出該數組峯值對應的索引位置
sample input:
6
1 8 9 10 7 5
sample output:
3


length = int(input())
message_list = list(map(int, input().strip().split(' ')))
for i in range(1, length - 1):
    if message_list[i] > message_list[i-1] and message_list[i] > message_list[i+1]:
        print(i)
        break


# 二分
# def find_top(message_list):
#     pivot = length // 2
#     if 1 < pivot < length - 1 and message_list[pivot] > message_list[pivot-1] and \
#             message_list[pivot] > message_list[pivot+1]:
#         print(pivot)
#         return 1
#
#     return find_top(message_list[:pivot+1]) or find_top(message_list[pivot+1:])
#
#
# find_top(message_list)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章