lintcode : find peak element 寻找峰值
2016-01-08 16:33
579 查看
题目
相邻位置的数字是不同的
A[0] < A[1] 并且 A[n - 2] > A[n - 1]
假定P是峰值的位置则满足
样例
给出数组
注意
数组可能包含多个峰值,只需找到其中的任何一个即可
解题
直接遍历
Java
Python
寻找峰值
你给出一个整数数组(size为n),其具有以下特点:相邻位置的数字是不同的
A[0] < A[1] 并且 A[n - 2] > A[n - 1]
假定P是峰值的位置则满足
A[P] > A[P-1]且
A[P] > A[P+1],返回数组中任意一个峰值的位置。
样例
给出数组
[1, 2, 1, 3, 4, 5, 7, 6]返回
1, 即数值 2 所在位置, 或者
6, 即数值 7 所在位置.
注意
数组可能包含多个峰值,只需找到其中的任何一个即可
解题
直接遍历
Java
class Solution { /** * @param A: An integers array. * @return: return any of peek positions. */ public int findPeak(int[] A) { // write your code here if(A == null || A.length == 0) return -1; if(A.length == 1) return 0; for(int i=1;i<A.length-1; i++){ if(A[i] >A[i-1] && A[i] >A[i+1]) return i; } if(A[0]>A[1]) return 0; if(A[A.length-1] >A[A.length - 1]) return A.length - 1; return -1; } }
Python
class Solution: #@param A: An integers list. #@return: return any of peek positions. def findPeak(self, A): # write your code here if A == None or len(A) ==0: return -1 for i in range(1,len(A)-1): if A[i]>A[i-1] and A[i]>A[i+1]: return i if A[0]>A[1]: return 0 if A[len(A)-1] >A[len(A)-2]: return len(A)-1 return -1
相关文章推荐
- iOS 之NSJSONReadingOptions说明【转】
- 利用maya+poser合成kinect 训练数据
- 网络编程归纳总结一阶段
- 高斯消元法解方程Ax=b的C源代码实现
- SDK开发笔记—— 代码和资源分离发布 sdk
- WinMain函数
- android-Transferring Data Using Sync Adapters
- LeetCode 题目总结/分类
- unity 中clear和深度ztest zwrite问题
- Hibernate--最佳实践 重要
- 租约机制简介
- 3.5.2赋值运算
- 22-《电子入门趣谈》第四章_自己制作电路板-4.3Altium Designer (第一部分)
- 适配器模式 c#
- Canvas与Image互转
- 英文条码创建/打印/java调windows API(方向)2
- 64位centos6.5安装mysql-5.6.25问题解决
- 为应用程序池**提供服务的进程意外终止。进程ID是**。进程退出代码是'0x80'
- 插入排序
- 对于用VS2013操作Word时编译失败的问题可以完美解决