leetcode 162. Find Peak Element-查找峰元素|二分查找
来源:互联网 发布:saas模式软件 编辑:程序博客网 时间:2024/05/22 04:49
原题链接:162. Find Peak Element
【思路-Java、Python】 二分查找
题目中已经说明,最左端和最右端元素均无限小,中间元素比两侧都要大,那么本题中一定存在一个峰元素。所以不管中间有多少波峰,只要找到峰元素,我们只需找到刚刚开始下降而未下降的位置。采用二分查找,查出这样一个位置即可,我们知道二分查找要比较的是 target 元素,本题的 target 元素是 mid 的后一个元素,即 nums[mid] 与 nums[mid+1] 进行比较:
public class Solution { public int findPeakElement(int[] nums) { int left = 0, right = nums.length - 1; while (left < right) { int mid = (left + right) / 2; if(nums[mid] < nums[mid + 1]) left = mid + 1; else right = mid; } return left; }}58 / 58 test cases passed. Runtime: 0 ms Your runtime beats 33.05% of javasubmissions.
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 while left < right : mid = (left + right) / 2 if nums[mid] < nums[mid + 1] : left = mid + 1 else : right = mid return left58 / 58 test cases passed. Runtime: 52 ms Your runtime beats 94.19% of pythonsubmissions.
1 0
- leetcode 162. Find Peak Element-查找峰元素|二分查找
- leetcode-二分查找:Find Peak Element
- LeetCode Find Peak Element(二分查找法)
- LeetCode OJ 之 Find Peak Element (查找极大元素)
- Leetcode 162 Find Peak Element 查找峰值元素(极大值)
- 二分查找——Find Peak Element
- 162. Find Peak Element 一次遍历或二分查找
- LeetCode 162. Find Peak Element(查找峰值)
- [C++]LeetCode: 118 Find Peak Element (二分查找 寻找数组局部峰值)
- LeetCode-162. Find Peak Element (JAVA)寻找peak元素
- LintCode Find Peak Element(查找峰值)
- [leetcode] 162 Find Peak Element(二分)
- Leetcode 162 - Find Peak Element(二分)
- [LeetCode]162.Find Peak Element
- LeetCode 162. Find Peak Element
- [leetcode] 162.Find Peak Element
- 【LeetCode】162. Find Peak Element
- Leetcode 162. Find Peak Element
- Java原始类型和引用类型
- bootstrap 模态框生成标签页
- Cocos2d-x 面试题解
- TCP 三次握手 长连接/短连接
- ACM:蓝桥杯:小学生算数
- leetcode 162. Find Peak Element-查找峰元素|二分查找
- 排序
- machine learning in action 之始 —— 重新出发
- js扩展方法
- Version 1.6.0_65 of the JVM is not suitable
- 严重: IOException while loading persisted sessions: java.io.EOFException
- c++作业7
- ACM:蓝桥杯:凑算式
- 【块状链表】【SCOI2006】动态最值