python求解LeetCode习题Find Peak Element in Given num_list

来源:互联网 发布:网络黑白txt百度云盘 编辑:程序博客网 时间:2024/05/17 21:58

题目

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 

翻译:

给定一个随机数组,找到里面的比左邻右舍都大的元素返回下标
思路:
与上一篇博文思路类似,只需要遍历的时候更新临时变量即可,这里要注意,起始和结束位置的比较,还有返回下标,我返回了元素和下标
具体实现如下:


#!usr/bin/env python#encoding:utf-8'''__Author__:沂水寒城功能:Find Peak Element in Given num_list'''def find_peek_element(num_list):    '''    对给定数组寻找比左邻右舍都大的元素    '''    result_list=[]    index_list=[]    length=len(num_list)    for i in range(1,length-2):        j=i+1        if num_list[j]>num_list[i] and num_list[j]>num_list[j+1]:            result_list.append(num_list[j])            index_list.append(j)    print '  Peak_element_list     is:', result_list    print 'Peak_element_index_list is:', index_listif __name__ == '__main__':    num_list=[1,2,3,6,9,4,5,7,6,8,9,0]    find_peek_element(num_list)

结果如下:

  Peak_element_list     is: [9, 7, 9]Peak_element_index_list is: [4, 7, 10][Finished in 0.2s]




原创粉丝点击